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. Here's an example:
from myapp.models import MyModel
not_equal_value = 'some value'
results = MyModel.objects.exclude(field_name=not_equal_value)
Watch a video course
Python - The Practical Guide
You can also chain filter()
and exclude()
together to filter out records that match multiple conditions:
results = MyModel.objects.filter(field1=value1).exclude(field2=value2)
You can also use the ~Q()
for not equal.
from django.db.models import Q
results = MyModel.objects.filter(~Q(field_name=not_equal_value))
You can also use the ne
keyword to filter out records where a certain field is not equal to a certain value.
results = MyModel.objects.filter(field_name__ne=not_equal_value)