postgresql 如何在django过滤器中做小于或等于和大于等于?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34743988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:07:49  来源:igfitidea点击:

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

pythondjangopostgresql

提问by Mohideen bin Mohammed

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<=50in django view.
For this I used some query in sql like this :-

如何在django过滤器中做小于或等于和大于等于?就像,我想在 :-10<=val<=50在 Django 视图中获得价值。
为此,我在 sql 中使用了一些查询,如下所示:-

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

I tried something like this in django view :-

我在 Django 视图中尝试过这样的事情:-

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.

但我得到了不同的价值观。在 sql 中我得到了 65,在 django 中我得到了 29。sql 答案是正确的。请帮我在 Django 视图中进行比较。

回答by mikeb

Why don't you use the _range function?

为什么不使用 _range 函数?

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

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

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

请参阅此处: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

编辑新链接:https: //docs.djangoproject.com/en/3.0/ref/models/querysets/#range

回答by doru

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

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

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