Categories
Python Answers

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

Spread the love

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 ~.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *