Reputation: 3690
For example, I have 2 querysets:
q1=MyModel.objects.filter(visible=True)
q2=MyModel.objects.filter(published=True)
And i need to make single queryset or list having all objects from q1 and q2.
I used to do it like this:
q=list(chain(q1,q2))
#q= q1 | q2 #this gives me not all objects from q2 or q1,so i don't use bitwise or
But it was said, that list()
will produce extra queries to database. Is it true? And if it is, can somebody specify the most optimized way to do the merge?
Upvotes: 0
Views: 295
Reputation: 8488
You can try to do this:
q1_pks = MyModel.objects.filter(visible=True).values_list('pk', flat=True)
q2_pks = MyModel.objects.filter(published=True).values_list('pk', flat=True)
final_query = MyModel.objects.filter(pk__in=list(q1_pks).extend(list(q2_pks)))
That should do the trick, although i'm not sure if those list(qX_pks)
produce performances issues or not.
Upvotes: 1
Reputation: 22808
q1=MyModel.objects.filter(visible=True)
q2=MyModel.objects.filter(published=True)
qs12 = QuerySetSequence(qs1, qs2)
Combine the above code with this snippet: http://djangosnippets.org/snippets/1933/
Upvotes: 1