Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

In the Django model QuerySets, I see that there is a __gt and __lt for comparative values, but is there a __ne/!=/<> (not equals?)

I want to filter out using a not equals:

Example:

Model: bool a;

int x;

I want

results = Model.objects.exclude(a=true, x!=5)

The != is not correct syntax. I tried __ne, <>.

I ended up using:

results = Model.objects.exclude(a=true, x__lt=5).exclude(a=true, x__gt=5)

1 Answer

0 votes
by (106k points)

You can use Q()objects that could be helpful for this problem. Q()objects can be negated and combined much like normal python expressions.

Q() object:-

Q() object encapsulates a SQL expression in a Python object that can be used in database-related operations.

You can use the following piece of code to solve not equal to a problem in Django.

from myapp.models import Entry 

from django.db.models import Q 

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

Related questions

0 votes
1 answer
asked Oct 12, 2019 in Web Technology by Rajesh Malhotra (19.9k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...