dease
dease

Reputation: 3076

Django combine multiple querysets (same model)

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?

Upvotes: 5

Views: 5004

Answers (3)

christian80gabi
christian80gabi

Reputation: 1

If you are using at least Django 3.2, this looks like

>>> qs1 = Author.objects.values_list('name')
>>> qs2 = Entry.objects.values_list('headline')
>>> qs1.union(qs2).order_by('name')

here is the link to documentation.

Upvotes: 0

Jose Cherian
Jose Cherian

Reputation: 7707

If you are using at least Django 1.11, this is a one liner.

final_results = result_elms[0].union(*result_elms[1:])

here is the link to documentaion. You may refer to my blog post for more examples.

Upvotes: 0

thebjorn
thebjorn

Reputation: 27311

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.

Upvotes: 6

Related Questions