How can I find the union of two Django querysets?
Question:
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?
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()
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.
I would suggest using ‘query1.union(query2)’ instead of ‘query1 | query2’;
I got different results from the above two methods and the former one is what I expected.
The following is what I had come across:
print "union result:"
for element in query_set1.union(query_set2):
print element
print "| result:"
for element in (query_set1 | query_set2):
print element
result:
union result:
KafkaTopic object
KafkaTopic object
KafkaTopic object
KafkaTopic object
KafkaTopic object
| result:
KafkaTopic object
KafkaTopic object
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?
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()
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.
I would suggest using ‘query1.union(query2)’ instead of ‘query1 | query2’;
I got different results from the above two methods and the former one is what I expected.
The following is what I had come across:
print "union result:"
for element in query_set1.union(query_set2):
print element
print "| result:"
for element in (query_set1 | query_set2):
print element
result:
union result:
KafkaTopic object
KafkaTopic object
KafkaTopic object
KafkaTopic object
KafkaTopic object
| result:
KafkaTopic object
KafkaTopic object