">", "<", ">=" and "<=" don't work with "filter()" in Django

Question:

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?

Asked By: Finglish

||

Answers:

Greater than:

Person.objects.filter(age__gt=20)

Greater than or equal to:

Person.objects.filter(age__gte=20)

Less than:

Person.objects.filter(age__lt=20)

Less than or equal to:

Person.objects.filter(age__lte=20)

You can find them all in [the documentation].(https://docs.djangoproject.com/en/stable/ref/models/querysets/).

Answered By: lprsd

Put __gt suffix for "Greater Than" to the field name age:

Person.objects.filter(age__gt=20)
                    #    ↑↑↑↑ 
                    # age > 20

Put __gte suffix for "Greater Than or Equal to" to the field name age:

Person.objects.filter(age__gte=20)
                    #    ↑↑↑↑↑ 
                    # age >= 20

Put __lt suffix for "Less Than" to the field name age:

Person.objects.filter(age__lt=20)
                    #    ↑↑↑↑ 
                    # age < 20

Put __lte suffix for "Less Than or Equal to" to the field name age:

Person.objects.filter(age__lte=20)
                    #    ↑↑↑↑↑ 
                    # age <= 20
Answered By: Kai – Kazuya Ito
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.