How to Merge QuerySets in Django?

Published On: 21/11/2022 | Category: Django

Hi Dev,

I am going to explain you example of how to merge querysets in django. let’s discuss about django merge queryset example. I explained simply step by step django combine two queryset from different models. you'll learn how to merge two querysets in django.

When you want to combine two or more querysets into one queryset without sacrificing the ability to perform filter, count, distinct, etc. operations, this tip is especially helpful.

Here i explained simply step by step example of how to merge querysets in django.

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example

Step 2: Create a App

Now we'll create a single app called core to store a list of post names. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.

python startapp core

Step 3: Create a Model

In this step we will require the database model for storing contacts.Open the todo/ file and add the following code:

from django.db import models

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

class Medium(models.Model):
    name = models.CharField(max_length=30, unique=True)
    stories = models.ManyToManyField(Story)

Ok, all set. We can engender a migrations file for this change, then integrate it to our database via migrate.

python makemigrations
python migrate

Consider the scenario where you want to show all the articles published in a particular Medium along with articles written by Users using the Category django. Please take note that this user may have written stories for other Mediums:

medium = Medium.objects.get(name='Django Blog')
user = User.objects.get(username='vitor')

django_stories = medium.stories.all()
vitor_stories = user.stories.filter(category__name='django')

Currently, we have two distinct querysets: one contains all stories from a particular medium, and the other contains all stories from a particular user using the Django category.

Using the | operator, the querysets can be combined as shown in the example below:

stories = django_stories | vitor_stories  # merge querysets

And you still can perform queryset operations:

recent_stories = stories.distinct().order_by('-date')[:10]

It's crucial to keep in mind that the merge/combine operator | only functions on querysets that come from the same model and are run before it has been split.

I Hope It will help you....