Consider two QuerySet objects of the same class. Is there a simple way to unify them into a single QuerySet by calculating the union? Also, is there a simple way to subtract the
Since Django 1.11, QuerySets have union(), intersection() and difference() methods.
It's also possible to use & and | operators with QuerySets (I could not find a reference to this in the docs, so I guess union()
and intersection()
is the preferred way to combine two querysets.
qs3 = qs1.union(qs2) # or qs3 = qs1 | qs2
qs3 = qs1.intersection(qs2) # or qs3 = qs1 & qs2
qs3 = qs1.difference(qs2) # the ^ operator is not implemented.
You can also use Q() objects which like QuerySets implement |
and &
, and additionally the inversion operator ~