Exclude one or multiple objects from Django Queryset
In this tutorial, we will learn how to exclude one or multiple objects from Django Queryset.
To learn more about Querysets click on the link given below:-
What is Django QuerySet and to execute one? (Part X)
Exclude() in Django
First and foremost, we must understand the exclude() method.
Django’s exclude () method basically returns a new QuerySet containing the objects that do not match the given parameter.
To exclude one object from Django Queryset follow the given steps:-
Step 1 : Start Project
Step 2 : Start App
Step 3 : Create a model in models.py
Step 1-Start Project
Start a new Django project.
Create a project named exclude by using command line django-admin startproject exclude
.
This will create a project.
Step 2-Start App
Start your app.
We will create an app inside our project in our current working directory.
To start app run django-admin startapp queryset
in the terminal. This will start an app inside the project named exclude.
Step 3-Create models.py
Before using exclude() method we will make model and then we will add records.
So in models.py write down the below code:-
from django.db import models class records(models.Model): heading = models.CharField(max_length=20) content = models.TextField() def __str__(self): return self.heading
After doing this we need to create a superuser. To do so run python manage.py createsuperuser
in the terminal it will ask you for some details like username, email and password and then we need to migrate changes we have made in our project. So run command python manage.py makemigrations
and python manage.py migrate
.
As we have created superused now we need to login using the same credentials on the link http://127.0.0.1:8000/admin.
Now, add records in the same.
Exclude one object from queryset
Now we will exclude one object from django queryset.
Syntax for using exclude() method :-
.exclude(field_name = "name of your title or heading")
To run a queryset we have to run the commands in shell, for this, we have to run the command python manage.py shell
.
To use models we need to import it by the below command:
from queryset.models import records
Now we will execute exclude() method:-
records.objects.exclude(heading = "Age")
It will return all objects except heading = “Age”.
Output:-
<QuerySet [<records: Student>, <records: City>]>
Exclude multiple objects from queryset
To exclude multiple objects from a queryset, we will use the exclude() methed along with in filter.
In the shell run command:
from queryset.models import records
And then assign the queryset names which you have to exclude in the variable named “a”.
a = ["Age", "City"]
After this run the below command:
records.objects.exclude(heading__in = a)
Output of the above code is:
<QuerySet [<records: Student>]>
Thanks for reading, I hope you found this tutorial helpful.
Happy Coding!
Hello,
Thanks for the tutorial, it helped me a lot!!!!