Django Objects Filter Not Equal Example

Published On: 17/08/2022 | Category: Django


Hi Dev,

This tutorial will provide example of django objects filter not equal example. it's simple example of django objects filter not equal. This post will give you simple example of django filter not equal. we will help you to give example of not in django query. Let's get started with django objects filter not equal example tutorial.

Django exclude() method filter all the data that does not match the given condition the objects that do not match the given lookup parameters and return a new queryset.

You can use these examples with django3 (Django 3) version.

let's see bellow example here you will learn exclude one or multiple objects from django queryset example.

Django Admin Interface:



Example 1: Using Exclude

In this example we will use the same Employee model. And here is the example of the exclude() method.

views.py
from django.http import HttpResponse
from core.models import Employee

def exclude(request):
    queryset = Employee.objects.exclude(firstname__startswith='B').values()
    #print QuerySet
    print(queryset)

    return HttpResponse(queryset)
Output
[
    {
        'id': 2,
        'firstname': 'Vishal',
        'lastname': 'Patel'
    },
    {
        'id': 3,
        'firstname': 'Nikhil',
        'lastname': 'Patel'
    }
]
Example 2: Using Q Objects

In this second example you can use Q objects for this. They can be negated with the ~ operator and combined much like normal Python expressions:

views.py
from django.http import HttpResponse
from core.models import Employee
from django.db.models import Q

def exclude(request):
    queryset = Employee.objects.filter(~Q(id=2)).values()
    #print QuerySet
    print(queryset)

    return HttpResponse(queryset)
Output
[
    {
        'id': 1,
        'firstname': 'Bhavesh',
        'lastname': 'Sonagra'
    },
    {
        'id': 3,
        'firstname': 'Nikhil',
        'lastname': 'Patel'
    }
]

I Hope It will help you....