Menu Close

How to do a not equal in Python Django queryset filtering?

Sometimes, we want to do a not equal in Python Django queryset filtering.

In this article, we’ll look at how to do a not equal in Python Django queryset filtering.

How to do a not equal in Python Django queryset filtering?

To do a not equal in Python Django queryset filtering, we can negate a equal with ~.

For instance, we write

from myapp.models import Entry
from django.db.models import Q

Entry.objects.filter(~Q(id=3))

to call filter with the Q object negated with ~ to return all the Entry results that don’t have id 3.

Conclusion

To do a not equal in Python Django queryset filtering, we can negate a equal with ~.

Posted in Python, Python Answers