结合2个Django查询集

时间:2018-02-22 22:00:46

标签: python django

我想使用操作数“|”在Django中合并两个queryset但它不起作用。我知道要做到这一点,你必须拥有来自同一模型的查询集。这正是我想要做的。循环是因为我想获得随机对象并将其合并为一个。任何人都知道为什么Django抛出“TypeError:不支持的操作数类型为|:'Sentence'和'Sentence'”错误?

根据以下来源,这是如何实现它: https://simpleisbetterthancomplex.com/tips/2016/06/20/django-tip-5-how-to-merge-querysets.html

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)

1 个答案:

答案 0 :(得分:0)

不在解释器附近,但是,您要合并两个对象而不是两个查询集。尝试用过滤器替换get。来自随机导入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.filter(pk=next_pk)
    type(sentence_qs)

    if i > 1:
       sentence_qs = sentence_qs | Sentence.objects.filter(pk=next_pk)