254

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?

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Finglish
  • 9,692
  • 14
  • 70
  • 114

2 Answers2

504

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/).

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
lprsd
  • 84,407
  • 47
  • 135
  • 168
0

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
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129