简体   繁体   中英

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.

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

如果你真的想使用>=<=你可以写:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM