Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the union of two Django querysets?

I’ve got a Django model with two custom manager methods. Each returns a different subset of the model’s objects, based on a different property of the object.

Is there any way to get a queryset, or just a list of objects, that’s the union of the querysets returned by each manager method?

like image 539
Paul D. Waite Avatar asked Dec 10 '10 16:12

Paul D. Waite


People also ask

How do I join two Querysets in Django?

Use union operator for queryset | to take union of two queryset. If both queryset belongs to same model / single model than it is possible to combine querysets by using union operator. One other way to achieve combine operation between two queryset is to use itertools chain function.

What is Union in Django?

The UNION operator is used to combine the result-set of two or more querysets. The querysets can be from the same or from different models.


2 Answers

This works and looks a bit cleaner:

records = query1 | query2 

If you don't want duplicates, then you will need to append .distinct():

records = (query1 | query2).distinct() 
like image 89
Jordan Reiter Avatar answered Oct 03 '22 09:10

Jordan Reiter


Starting from version 1.11, django querysets have a builtin union method.

q = q1.union(q2) #q will contain all unique records of q1 + q2 q = q1.union(q2, all=True) #q will contain all records of q1 + q2 including duplicates q = q1.union(q2,q3) # more than 2 queryset union 

See my blog post on this for more examples.

like image 34
Jose Cherian Avatar answered Oct 03 '22 11:10

Jose Cherian