combine django querysets

How to Combine Querysets in Django

Django querysets allow you to query different database models and get results. But sometimes you may need to merge querysets in Django to consolidate the results. Typically, people create an empty list, loop through each query set and append each row’s value to the empty list to build the combined result. But this is a very slow and memory intensive process. In this article, we will look at a much simpler and faster way to combine querysets in Django, using itertools.


How to Combine Querysets in Django

Here are the steps to combine querysets in Django. Let us say you have two queryset results called user_list and people_list. Here is the python code to combine querysets in Django.

from itertools import chain
result_list = list(chain(user_list, people_list))

In this code, we use chain function in itertools. We pass the querysets that we want to combine, as comma-separated arguments to chain function. We convert the result of chain function into a list, which we store in result_list variable.

Using itertools is faster than looping, since it is written in C programming language and consumes less memory than converting each queryset into list.

You can even sort the combined queryset using sorted function, as shown. In this case, we use a generator to the id column to sort the combined queryset.

Let us say, both user and people models have id column. In the following example, we are sorting the combined queryset based on id column, present in both user and people models.

result_list = sorted(
    chain(user_list, people_list),
    key=lambda instance: instance.id)

In this short article, we have learnt how to combine Django querysets.

Also read:

How to Get Field Value in Django
How to Convert Markdown to HTML in Python
How to Configure DNS Server in RHEL/CentOS
Python Delete Dictionary Key While Iterating
Python Remove Item from List While Iterating

Leave a Reply

Your email address will not be published. Required fields are marked *