How to Merge QuerySets in Django

Learn how to merge two or more querysets into a single queryset

Picture of Nsikak Imoh, author of Macsika Blog
White image with the text How to Merge QuerySets in Django
White image with the text How to Merge QuerySets in Django

This post is part of the tutorial series titled Learn to Use Django with FastAPI Frameworks

Table of Content

When working with Django, there might be a need to merge two querysets and run operations on them.

Here's how to merge two or more querysets into a single queryset without losing the capabilities of performing filter, count, distinct, etc. operations.

Take the following models as an example:

class Show(models.Model):
    title = models.CharField(max_length=255)
    content = models.TextField(blank=True)
    category = models.ForeignKey(Category, related_name='shows')
    author = models.ForeignKey(User, related_name='shows')

class Channel(models.Model):
    name = models.CharField(max_length=30, unique=True)
    shows = models.ManyToManyField(Show)
Highlighted code sample.

Assuming you have a task to display all the shows posted in a specific Channel together with shows written by a User using the Category fiction.

Note that this User might have posted some shows in a different Channel:

channel = Channel.objects.get(name='Channel 15')
user = User.objects.get(username='nsikak')

fiction_shows = channel.shows.all()
nsikak_shows = user.shows.filter(category__name='comedy')
Highlighted code sample.

At this point, we have two different querysets.

One contains all the shows from a channel and the other contains all the shows from a user using the comedy category.

Here comes the task of merging them.

How to Merge QuerySets in Django

The querysets can be merged, using the pipe | operator:

Checkout the example below:

shows = comedy_shows | nsikak_stories  # merge querysets
Highlighted code sample.

And you still can perform queryset operations:

recent_shows = shows.distinct().order_by('-date')[:10]
Highlighted code sample.

What you Should Know When Merging QuerySets in Django

  • Mering with the pipe operator | only works on querysets from the same model.

  • You need to merge before performing slicing on either of the querysets.

Wrap Off

There you have it! I hope you found this post useful somehow.

If you have any questions or need clarification, feel free to reach out to me.

If you learned from this tutorial, or it helped you in any way, please consider sharing and subscribing to our newsletter.

Get the Complete Code of Django and FastAPI Combo Tutorials on Github.

Connect with me.

Need an engineer on your team to grease an idea, build a great product, grow a business or just sip tea and share a laugh?