How Can I Combine Two or More QuerySets in a Django View?

How Can I Combine Two or More QuerySets in a Django View?

How to do union of two querysets from same or different models?

Assume you got two querysets from one or more models, and you want the querysets to combine into one, for that Django ORM provides a union method to combine those querysets.

The querysets can be from the same or from different models, just one thing to note here is that when the querysets are from different models, the fields and their data types must match.

Let’s have a look at this example of combing two querysets of same User model:

qs1 = User.objects.filter(id__gte=3)
# <QuerySet [<User: Ritesh>, <User: Billy>, <User: Radha>, <User: sohan>, <User: Raghu>, <User: rishab>]>

qs2 = User.objects.filter(id__lte=6)
# <QuerySet [<User: John>, <User: Ricky>, <User: Ritesh>, <User: Billy>, <User: Radha>, <User: sohan>]>

qs = qs1.union(qs2)
# <QuerySet [<User: John>, <User: Ricky>, <User: Ritesh>, <User: Billy>, <User: Radha>, <User: sohan>, <User: Raghu>, <User: rishab>]>

# We can also switch the places of qs1 and qs2 the results will be same
qs = qs2.union(qs1)
# <QuerySet [<User: John>, <User: Ricky>, <User: Ritesh>, <User: Billy>, <User: Radha>, <User: sohan>, <User: Raghu>, <User: rishab>]>

Let's understand how can we combine two querysets from two or more difference models: (But before that, keep in mind, when the querysets are from different models, the fields and their data types must match.)

qs1 = Author.objects.values_list('name')

qs2 = Entry.objects.values_list('headline')

qs = qs1.union(qs2)
# django.db.utils.OperationalError: SELECTs to the left and right of UNION do not have the same number of result columns

As you can see above that we got a OperationalError while performing the union of two querysets from different models.

Let’s check out, when we can union two queryetes of different models:

qs1 = Hero.objects.all().values_list("name", "gender")

qs2 = Villain.objects.all().values_list("name", "gender")

qs = qs1.union(qs2)

Above code will print the correct output without any errors, as we are performing the union based on two columns 'name' and 'gender' and both have same data types.

Any thoughts? Write it down in the comments.

For more such crispy blogs daily, follow Dev.Junction, subscribe to our newsletter and get notified.

Did you find this article valuable?

Support Dev.Junction by becoming a sponsor. Any amount is appreciated!