With =
below, I could filter persons by age
:
qs = Person.objects.filter(age = 20)
# ↑ Here
But with >
, <
, >=
and <=
below, I couldn't filter persons by 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
How can I do greater than(>)
, greater than or equal to(>=)
, less than(<)
and less than or equal to(>=)
with filter() in Django?
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. 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
:
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
:
Person.objects.filter(age__gte=20)
# ↑↑↑↑↑
# age >= 20
Put __lt suffix for " L ess T han" to the field name 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
:
Person.objects.filter(age__lte=20)
# ↑↑↑↑↑
# age <= 20
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.