Django combine multiple querysets (same model)

Viewed 4755

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?

2 Answers

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.

Related