W3docs

How do I do a not equal in Django queryset filtering?

You can use the exclude() method to filter out records where a certain field is not equal to a certain value.

You can use the exclude() method to filter out records where a certain field does not match a specific value. Here's an example:

Using exclude() for simple negation

from myapp.models import MyModel

not_equal_value = 'some value'
results = MyModel.objects.exclude(field_name=not_equal_value)

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

You can also chain filter() and exclude() together to apply multiple conditions:

Chaining filter() and exclude() for multiple conditions

results = MyModel.objects.filter(field1=value1).exclude(field2=value2)

Alternatively, you can use the Q object with the bitwise NOT operator (~) to achieve the same result:

Using Q objects for negation

from django.db.models import Q
results = MyModel.objects.filter(~Q(field_name=not_equal_value))

When to use exclude() vs Q() objects

Both approaches generate identical SQL (WHERE field != value). Use exclude() for straightforward single-condition negation. Use Q() objects when you need to combine negation with complex OR/AND logic inside a single filter() call, as chaining exclude() after filter() applies an AND condition rather than an OR.