How can I do not equal in Django queryset filtering

0 votes

In Django model QuerySets, I see that there is a __gt and __lt for comparative values, but is there a __ne or != (not equals)? I want to filter out using a not equals. For example, for

Model:
    bool a;
    int x;

I want to do

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

The != is not correct syntax. I also tried __ne.

I ended up using:

results = Model.objects.exclude(a=True, x__lt=5).exclude(a=True, x__gt=5)
Nov 17, 2020 in Python by kartik
• 37,520 points
808 views

1 answer to this question.

0 votes

Hello @kartik,

You can use Q objects for this. They can be negated with the ~ operator and combined much like normal Python expressions:

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

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

will return all entries except the one(s) with 3 as their ID:

[<Entry: Entry object>, <Entry: Entry object>, <Entry: Entry object>, ...]
answered Nov 17, 2020 by Niroj
• 82,840 points

Related Questions In Python

0 votes
1 answer

How do I perform query filtering in django templates?

Hello @KARTIK, Just add an extra template tag ...READ MORE

answered Jul 4, 2020 in Python by Niroj
• 82,840 points
12,716 views
0 votes
1 answer

How can I have only positive decimal numbers in Django using Python?

Hi, are you aware of something called ...READ MORE

answered Jan 30, 2019 in Python by Nymeria
• 3,560 points
6,352 views
0 votes
1 answer

How do I check if input string is a valid regular expression or not in Python?

Hi. Good question! Well, just like what ...READ MORE

answered Feb 12, 2019 in Python by Nymeria
• 3,560 points
11,318 views
0 votes
1 answer

How can I prevent brute force login attacks using Django in Python?

Hi. Django-axes is an already existing application ...READ MORE

answered Feb 15, 2019 in Python by Nymeria
• 3,560 points
2,439 views
0 votes
1 answer

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

Hello @kartik, Try this code below: >>> from myapp.models ...READ MORE

answered Jul 3, 2020 in Python by Niroj
• 82,840 points
4,707 views
0 votes
1 answer

How to do a not equal in Django queryset filtering?

Hello @kartik, Your query appears to have a ...READ MORE

answered Jun 26, 2020 in Python by Niroj
• 82,840 points
28,507 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP