I want to merge two queryset in Django using operand "|" but it don't work. I know that to do it you must have querysets from the same model. This is exactly what I'm trying to do. The loop is because I want to get random objects and merge it into one. Anyone have idea why Django throw "TypeError: unsupported operand type(s) for |: 'Sentence' and 'Sentence'" error?
According to below source this is how to make it happen: 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
and not twoquerysets
. Try replacingget
withfilter
. – Borko Kovacev