I have list of querysets (all for same model):
results = Entry.objects.all()
result_elms = []
if city_list:
for city in city_list:
result_elms.append(results.filter(address__city__icontains=city))
if county_list:
for county in county_list:
results_elms.append(results.filter(address__county__icontains=county))
#other filters here, daynamically created
#how can I combine all results_elms (querysets) into one?
I know that I can use |
operator to combine querysets from same model.
But how can I apply it for all elements from result_elms
list?
Join can be done with select_related method: Django defines this function as Returns a QuerySet that will “follow” foreign-key relationships, selecting additional related-object data when it executes its query.
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.
Django-filter is a generic, reusable application to alleviate writing some of the more mundane bits of view code. Specifically, it allows users to filter down a queryset based on a model's fields, displaying the form to let them do this. Adding a FilterSet with filterset_class. Using the filterset_fields shortcut.
Related, for mixing querysets from the same model, or for similar fields from a few models, starting with Django 1.11 a QuerySet.union () method is also available: New in Django 1.11. Uses SQL’s UNION operator to combine the results of two or more QuerySets.
Using Union operator If both your querysets belong to the same model, such as q1 and q3 above, then you can use union operator | to easily combine those querysets. Here is an example to do it. You can use the union operator to combine two or more querysets as shown below.
Using itertools itertools provides chain method that allows you to easily combine two or more querysets from same or different models. Here is an example to combine q1 and q2 querysets defined above using itertools. from itertools import chain combined _list = list (chain (q1,q2))
Use union operator for queryset | to take union of two queryset. If both queryset belongs to same model / single model than it is possible to combine querysets by using union operator. One other way to achieve combine operation between two queryset is to use itertools chain function.
You can use Q
objects:
from django.db.models import Q
results = Entry.objects.all()
q = Q()
for city in city_list:
q = q | Q(address__city__icontains=city)
results.filter(q)
The documentation (https://docs.djangoproject.com/en/1.7/topics/db/queries/#complex-lookups-with-q) has more details and examples.
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