How do I do a not equal in Django queryset filtering

0 votes

In Django model QuerySets, I see that there is a __gt and __lt for comparitive 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)
Jul 3, 2020 in Python by kartik
• 37,520 points
4,704 views

1 answer to this question.

0 votes

Hello @kartik,

Try this code below:

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

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

[<Entry: Entry object>, <Entry: Entry object>, <Entry: Entry object>, ...]

Hope it helps!!

answered Jul 3, 2020 by Niroj
• 82,840 points

Related Questions In Python

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,315 views
+1 vote
1 answer

How do I create a slug in Django?

Hello @kartik, You will need to use the ...READ MORE

answered Jun 26, 2020 in Python by Niroj
• 82,840 points
1,276 views
+1 vote
1 answer

How do I return JSON without using a template in Django?

Hello @kartik, In the case of the JSON ...READ MORE

answered Jul 3, 2020 in Python by Niroj
• 82,840 points
4,873 views
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,706 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,840 points
2,505 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,840 points
1,580 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,499 views
0 votes
1 answer

How can I do not equal in Django queryset filtering?

Hello @kartik, You can use Q objects for this. They ...READ MORE

answered Nov 17, 2020 in Python by Niroj
• 82,840 points
806 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