[英]">", "<", ">=" and "<=" don't work with "filter()" in Django
With =
below, I could filter persons by age
:使用下面的
=
,我可以按age
过滤人员:
qs = Person.objects.filter(age = 20)
# ↑ Here
But with >
, <
, >=
and <=
below, I couldn't filter persons by age
:但是对于下面的
>
、 <
、 >=
和<=
,我无法按age
过滤人员:
qs = Person.objects.filter(age > 20)
# ↑ Here
qs = Person.objects.filter(age < 20)
# ↑ Here
qs = Person.objects.filter(age >= 20)
# ↑↑ Here
qs = Person.objects.filter(age <= 20)
# ↑↑ Here
Then, I got the error below:然后,我收到以下错误:
NameError: name 'age' is not defined
NameError:未定义名称“年龄”
How can I do greater than(>)
, greater than or equal to(>=)
, less than(<)
and less than or equal to(>=)
with filter() in Django?我如何在 Django 中使用filter()执行
greater than(>)
、 greater than or equal to(>=)
、 less than(<)
和less than or equal to(>=)
?
Less than or equal:小于或等于:
User.objects.filter(userprofile__level__lte=0)
Greater than or equal:大于或等于:
User.objects.filter(userprofile__level__gte=0)
Likewise, lt
for less than and gt
for greater than.同样,
lt
表示小于, gt
表示大于。 You can find them all in the documentation .您可以 在文档中找到它们。
The 1st answer works like a charm, to briefly explain it第一个答案就像一个魅力,简要解释一下
You just put the field you want to compare then the double underscore and您只需将要比较的字段放在双下划线和
gte means >=
lte means >=
gt means >
lt means <
The "level" in the first answer was supposedly a joint field name with userprofile from the question, it is not necessarily a key word第一个答案中的“级别”应该是问题中的用户配置文件的联合字段名称,不一定是关键字
Put __gt suffix for " G reater T han" to the field name age
:将“ G reater Than”的__gt后缀添加到字段名称
age
中:
Person.objects.filter(age__gt=20)
# ↑↑↑↑
# age > 20
Put__gte suffix for " G reater T han or E qual to" to the field name age
:将“ G reater Than or E qual to”的__gte后缀添加到字段名称
age
中:
Person.objects.filter(age__gte=20)
# ↑↑↑↑↑
# age >= 20
Put __lt suffix for " L ess T han" to the field name age
:将“小于”的__lt后缀添加到字段名称
age
中:
Person.objects.filter(age__lt=20)
# ↑↑↑↑
# age < 20
Put__lte suffix for " L ess T han or E qual to" to the field name age
:将“小于或等于”的__lte后缀添加到字段名称
age
中:
Person.objects.filter(age__lte=20)
# ↑↑↑↑↑
# age <= 20
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.