【发布时间】:2018-08-02 22:13:09
【问题描述】:
我想在 Django 中使用操作数“|”合并两个查询集但它不起作用。我知道要做到这一点,您必须拥有来自同一模型的查询集。这正是我想要做的。循环是因为我想获取随机对象并将其合并为一个。任何人都知道为什么 Django 抛出“TypeError: unsupported operand type(s) for |: 'Sentence' and '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)
【问题讨论】:
-
您正在合并两个
objects而不是两个querysets。尝试将get替换为filter。