How to make less or equal and more than in a django filter?

How to make less than or equal to or more than in a django filter? For example, I want to get the value around: - 10<=val<=50 in the django view.
For this, I used some query in sql as follows: -

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

I tried something like this in the django view: -

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

But I have different meanings. In sql, I got 65 and in django, I got 29. The sql answer is correct. Please help me make a comparison in the django view.

+5
source share
2 answers

Why aren't you using the _range function?

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

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

+10
source

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

 Modelname.objects.filter(gender='MALE', age__gte = 10, age__lte = 50).count() 
+8
source

Source: https://habr.com/ru/post/1240433/


All Articles