Exclude one or multiple objects from Django Queryset Example

Hi Dev,
This simple article demonstrates how to exclude one or multiple objects from Django QuerySet. We'll walk through using Django's powerful exclude()
method to filter out specific data. This method is especially useful when you want to get all records except those matching certain conditions.
Django's exclude()
method filters out the objects that match the specified lookup conditions and returns a new QuerySet with the rest of the results.
You can apply this in Django 3 and above easily. Let’s go step-by-step with real-world examples.
Create a ModelWe need a model first. Open the models.py and define an Employee model:
models.pyfrom django.db import models # Create your models here. class Employee(models.Model): firstname = models.CharField(max\_length=255) lastname = models.CharField(max\_length=255)
Django Admin Interface:

Example 1 : Exclude One Object from QuerySet views.py
from django.shortcuts import render from django.http import HttpResponse from core.models import Employee def exclude(request): employees = Employee.objects.exclude(firstname="Vishal").values() print(employees) return HttpResponse(employees)Output
\[ { 'id': 1, 'firstname': 'Mehul', 'lastname': 'Bagda' } ]Example 2 : Exclude Multiple Objects from QuerySet
Use __in
with the exclude()
method to skip multiple entries.
from django.shortcuts import render from django.http import HttpResponse from core.models import Employee def exclude(request): excludes = \['Mehul', 'Bhavesh'] employees = Employee.objects.exclude(firstname\_\_in=excludes).values() print(employees) return HttpResponse(employees)Output
\[ { 'id': 2, 'firstname': 'Mehul', 'lastname': 'Bagda' } ]
I Hope It will help you....
Frequently Asked Questions (FAQs)
Q1: What does exclude() do in Django?
It removes objects from the QuerySet that match the given lookup conditions.
Q2: Can I exclude multiple values in Django?
Yes, by using exclude(field__in=[value1, value2])
.
Q3: How is exclude() different from filter()?
filter()
returns matching records, exclude()
returns non-matching ones.
Q4: Is exclude() chainable in Django QuerySet?
Yes, you can chain exclude()
with other QuerySet methods.
Q5: Does exclude() impact database performance?
It runs SQL WHERE NOT
conditions and is generally efficient for most use cases.