Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do less than or equal to and greater than equal to in django filter?

How to do less than or equal to and greater than equal to in django filter? Like , I want to get value around :- 10<=val<=50 in django view.
For this I used some query in sql like this :-

select count(*) from table_name where gender='MALE' and age<=50 and age>=10;

I tried something like this in django view :-

tablename.objects.filter(Q(gender='MALE'),Q(age__lte=50) & Q(age__gte=10)).count()

But I got different values. In sql I got 65 and in django I got 29. sql answer is correct. Please help me to do comparison in django view.

like image 528
Mohideen bin Mohammed Avatar asked Jan 12 '16 12:01

Mohideen bin Mohammed


People also ask

How do I do a not equal in django QuerySet filtering?

To answer your specific question, there is no "not equal to" but that's probably because django has both "filter" and "exclude" methods available so you can always just switch the logic round to get the desired result.

What is __ GT in django?

The __lte lookup [Django-doc] means that you constrain the field that is should be less than or equal to the given value, whereas the __gte lookup [Django-doc] means that the field is greater than or equal to the given value. So for example: MyModel.objects. filter(field__gte=5) # field ≥ 5 MyModel.objects.

What is the purpose of filter () method in django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.


2 Answers

Why don't you use the _range function?

filter(gender='MALE', age__range=(10, 50))

See here: https://docs.djangoproject.com/en/1.7/ref/models/querysets/#range

Edit for new link: https://docs.djangoproject.com/en/3.0/ref/models/querysets/#range

like image 130
mikeb Avatar answered Oct 16 '22 13:10

mikeb


If you really want to use >= and <= yo could write:

Modelname.objects.filter(gender='MALE', age__gte = 10, age__lte = 50).count()
like image 20
doru Avatar answered Oct 16 '22 13:10

doru