Combine 2 Django Querysets
我想使用操作数""在Django中合并两个查询集,但它不起作用。我知道要做到这一点,您必须拥有来自同一模型的查询集。这正是我想做的。循环是因为我想得到随机的对象并将其合并为一个。有人知道为什么Django抛出"type error:unsupported operand type(s)for:'sentence'and'sentence'"错误吗?
根据以下来源,这是如何实现的:https://simpleisbetterhancomplex.com/tips/2016/06/20/django-tip-5-how-to-merge-queryset.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | from random import randint from sentences.models import Sentence sentence_number = 3 first_pk = Sentence.objects.first().pk last_pk = Sentence.objects.last().pk for i in range(sentence_number): next_pk = randint(first_pk, last_pk) sentence_qs = Sentence.objects.get(pk=next_pk) type(sentence_qs) if i > 1: sentence_qs = sentence_qs | Sentence.objects.get(pk=next_pk) |
不是在解释器附近,而是合并两个对象,而不是两个查询集。尝试用过滤器替换GET。从随机导入randint
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | from sentences.models import Sentence sentence_number = 3 first_pk = Sentence.objects.first().pk last_pk = Sentence.objects.last().pk for i in range(sentence_number): next_pk = randint(first_pk, last_pk) sentence_qs = Sentence.objects.filter(pk=next_pk) type(sentence_qs) if i > 1: sentence_qs = sentence_qs | Sentence.objects.filter(pk=next_pk) |