265

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?

3
  • 3
    @BéresBotond Although the docs look great - the structuring and layout is so poor that without a direct link, they are all but useless
    – RunLoop
    Commented Jul 6, 2015 at 4:41
  • @BéresBotond Unfortunately that link is now dead :(
    – dKen
    Commented Aug 30, 2016 at 18:59
  • Working link for doc: docs.djangoproject.com/en/1.11/ref/models/querysets/#gt Commented Jan 24, 2018 at 7:43

2 Answers 2

527

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

6
  • 3
    Wow, that was fast :). This works great for less than or equal, but how about just less than? (userprofile__level__lt=3) doesn't seem to work
    – Finglish
    Commented Apr 6, 2012 at 6:57
  • 2
    It does; but in any case, you can also do exclude(__gte) instead of filter(__lt).
    – lprsd
    Commented Apr 6, 2012 at 7:01
  • 7
    And do NOT forget that there are two __ underlines
    – andilabs
    Commented Jan 30, 2014 at 6:48
  • Im getting this error--> {FieldError}Unsupported lookup 'level' for AutoField or join on the field not permitted. Commented Sep 20, 2018 at 3:18
  • 2
    Remember change userprofile__level by your fields e.g. youtfield__lte. @AravindRPillai Commented Jul 3, 2022 at 23:33
1

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.