Combine two querysets in Django
Sometimes, we might need to combine two querysets in Django even from different models to execute a certain condition. In this tutorial, we will try to combine queryset using Django.
You can refer to the tutorial to know more about queryset and their execution https://www.codespeedy.com/django-queryset-and-to-execute/
Why to combine two querysets
When we need to combine results of two queryset, maybe from two different models, suppose we have so many entries but we need to find the students and faculties from a particular department but we have two models named student and teacher. Here we can separately find the results of two and at the end combine them, so we will get the desired result.
We can do the following to accomplish our given task
Step1 Make models
Open your models.py and make the model student and teacher with the following entries.
from django.db import models # Create your models here. class student(models.Model): name=models.CharField(max_length=20,unique=True) roll_number=models.IntegerField() dob=models.DateField() dept=models.CharField(max_length=60,default="CSE") def __str__(self): return self.name class teacher(models.Model): name=models.CharField(max_length=50) email=models.EmailField() mob_number=models.IntegerField() dept=models.CharField(max_length=60,default="CSE") def __str__(self): return self.name
Step2 Register your models
This is the code for models.py. Now, we will register our models in admin.py. So quickly open admin.py and register your model.
from django.contrib import admin from .models import student, teacher # Register your models here. admin.site.register(student) admin.site.register(teacher)
Your admin.py should look like above.
Step3 Install your app in settings.py
Open your settings.py file and add your app name in installed app section. I have named my app as app only. So this is what my installed apps section looks like:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app.apps.AppConfig', ]
You can know the name of your app inside the apps.py.
Step4 Create a superuser and migrate
Now it’s time to create a superuser to get all the access and surf into the admin panel.
python manage.py createsuperuser in your terminal. It will then ask you for some details. You will be asked to login using these details in admin section when we run server.
Also let’s migrate our models we have just created.
You just need to execute these commands on your terminal.
python manage.py makemigrations
python manage.py migrate
Step5 Add entries in models created
python manage.py runserverand navigate to your localhost http://127.0.0.1:8000 and append /admin and then login into Django administration using the credentials just created above and add entries.
Step6 Execute queries
Open your terminal and write python manage.py shell. It will open shell for you. Without any further delay, lets create our query and try to combine it.
The very first step is to import models.
from app.models import student,teacher
Then, we will execute queries to find all the students and teachers in CSE dept. We can execute the query as
This will filter all the entries where dept is CSE and it will save it in s1.
We will do the same for teachers.
We can combine s1 and t1 using itertools. So lets import chain from itertools which takes multiple iterables, combine and return it.
Start by importing chain as
from itertools import chain
We will display it in list form using:
It will show output according to my data:
[<student: Khushi>, <student: Tina>, <student: Atharv>, <student: Pranjul>, <student: Kratika>, <teacher: Prof. Sanchit Jain>, <teacher: Prof. Rajendra Gupta>, <teacher: Mrs. Roli Trivedi>, <teacher: Mrs. Purnima Jha>]
This is one method to create combined queries. Now lets move to the another one using union operator(|).
s4=s2 | s3
This is s4 variable which has combined result set of s2 and s3.
When we try to print s4 we get
<QuerySet [<student: Khushi>, <student: Pranjul>]>
which is the required queryset.
So in this tutorial we came across the topic and got a better understanding about queries and combining the results of various queryset.
Hope you enjoyed reading this tutorial and gained knowledge regarding this topic.