Django Queryset With an Unusual Operation "Merge"

Published on:
February 11, 2022

Consider, we have a StudentHistory model defined as:     

We can write two querysets on this model:   

Let's learn a bit about the Django queryset merging. We have three possible ways for merging the queryset.

1. If the querysets are of same model then we can use "|" (pipe) operator for merging querysets:

We can still perform operation on the merged queryset:

With | operator, we can only merge querysets of same model.

2. If the querysets are of different models, we can use "chain()" built-in function.

We also can sort the below merged_queryset on first_name using attrgetter function

Limitation: Chain function returns a list of objects instead of an queryset object. This can be problematic when the results are large in numbers and their pagination is needed.

3. Django queryset have in-built method "union()":

Union method can be used for merging querysets of same or different models.

Case1: If the querysets are of same model

Consider the StudentHistory model defined earlier in the post for below examples:

Case 2: If the querysets are of different models -

Now along with the already defined model StudentHistory we define another model Teacher below for this case:

Note - When models are different, union() function needs same named fields from the related model's querysets.


Thus we fetch only 3 same named fields i.e first_name, last_name, email. We can now perform union function on querysets:

Outsource the best Development team now!

You know what a great tech team can do to your business. It is time to act fast and outsource the best one. But who to pick or choose? MarsDevs got your back!

We have a team of developers who can build, deploy, and manage applications for you so that you can focus on the business better. As soon as you register, our expertise becomes yours! 

Do you have a project for us? We must connect as you can then share your requirements while we share our experience. You can book your slot now!

Similar Posts