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 them? Removing all elements that appear in both sets from one of the sets?
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. When they querysets are from different models, the fields and their datatypes should match.
To do a not equal in Python Django queryset filtering, we can negate a equal with ~ . to call filter with the Q object negated with ~ to return all the Entry results that don't have id 3.
A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.
This is because a Django QuerySet is a lazy object. It contains all of the information it needs to populate itself from the database, but will not actually do so until the information is needed.
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 ~
Subtract a QuerySet from another QuerySet using the same model.
This works - but is probably slowly
queryset_with_hello = Blog.objects.filter(name__icontains='hello') queryset_without_hello = Blog.objects.exclude(pk__in=queryset_with_hello)
Read the performance considerations in django documentation:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#in
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With