How can I find the union of two sets of Django requests?

I have a Django model with two custom methods. Each returns a different subset of model objects based on a different property of the object.

Is there a way to get a set of queries or just a list of objects, that is, combining the queries returned by each manager method?

+46
python django django-models
Dec 10 '10 at 16:32
source share
2 answers

This works and looks a little cleaner:

records = query1 | query2 

If you do not want to duplicate, you need to add .distinct() :

 records = (query1 | query2).distinct() 
+122
Dec 10 2018-10-10
source share

Starting with version 1.11 , django querysets have a built-in unified 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 for more details.

+11
Aug 09 '17 at 1:42 on
source share



All Articles