29👍
Since Django 1.11, QuerySets have union()
, intersection()
and difference()
methods.
It’s also possible to use &
and |
infix 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) # no operator for this
You can also use Q()
objects which like QuerySets implement |
and &
, and additionally the invert prefix operator ~
.
Neither class implement the xor / symmetric difference infix operator ^
.
19👍
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
- [Django]-How to update fields in a model without creating a new record in django?
- [Django]-How to insert data to django database from views.py file?
- [Django]-How can I get MINIO access and secret key?
16👍
Going back to django’s documentation, you can:
new_query_set = query_set_1 | query_set_2
This works as a logical OR which is actually addition without duplicates. This answers the addition aspect and AFAIK does not hit the db at all!
new_query_set = query_set_1 & query_set_2
This works as a logical AND.
Still missing how to subtract QuerySets. It’s hard for me to believe this has not been dealt with elegantly by the community…
- [Django]-What is a "slug" in Django?
- [Django]-How to add custom field in ModelSerializer?
- [Django]-How to add a sortable count column to the Django admin of a model with a many-to-one relation?
4👍
You can use the Q
object.
The syntax could be something like this:
added_query_set = YourModel.objects.\
filter(Q(id__in=old_query_set_1)|Q(id__in=old_query_set_2))
You probably can optimize based on your actual needs and get the amount of db hits down (right now it’s 3), but this should get you started.
- [Django]-Django: Is there a way to keep the dev server from restarting when a local .py file is changed and dynamically loaded?
- [Django]-You are trying to add a non-nullable field 'new_field' to userprofile without a default
- [Django]-How to serve media files on Django production environment?
- [Django]-Django TestCase testing order
- [Django]-How to check if a user is logged in (how to properly use user.is_authenticated)?
- [Django]-Django "get() got an unexpected keyword argument 'pk'" error
0👍
I think for operations as this you need to evalute them. So you can call list()
on them and work on them with the common python list operations!
- [Django]-Django – How to specify which field a validation fails on?
- [Django]-How do I require an inline in the Django Admin?
- [Django]-Separating form input and model validation in Django?