How to Perform a Not Equal in Django Queryset Filtering

To perform a “not equal” filter in a Django queryset, you can use the “exclude()” method and the field you want to filter. The exclude() method is the opposite of the filter() method: it returns a new queryset that only includes items that do not match the given condition.


from django.db import models

class Book(models.Model):
  title = models.CharField(max_length=100)
  author = models.CharField(max_length=100)

Let’s say you want to retrieve all books not authored by “Pranav Shah”.

You can use the exclude() method like this:

books_not_by_john_doe = Book.objects.exclude(author="Pranav Shah")

You can see that the books_not_by_john_doe queryset will contain all books where the author field is not equal to “Pranav Shah”.

That’s all!

Leave a Comment