Anibal Cardozo
Anibal Cardozo

Reputation: 577

How to filter a query on Django ORM

I know this should be pretty basic but somehow I don't quite get it. I want to get all users which age is lesser than 18 so the query should be something like this

User.objects.filter(age < 18)

what Im doing wrong?

Upvotes: 1

Views: 215

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477641

In order to filter with a less than filter, you use the __lt lookup [Django-doc]:

User.objects.filter(age__lt=18)

or if you want to filter on a property that is some expression of fields, you can first annotate:

from django.db.models import F

User.objects.annotate(
    age=F('age1') + F('age2')
).filter(age__lt=18)

or if you want to subtract a number:

from django.db.models import F

User.objects.annotate(
    ageminus=F('age') - 5
).filter(ageminus__lt=18)

In this example the User object has no age field, but an age1 and age2 field. First we thus introduce an annotation age, that is the sum of these two fields.

By writing .filter(age < 18), the Python interpreter will look for a variable named age, and if that indeed exists (not per), then it will compare that with 18, and pass the result as a positional parameter to filter(..). So unless you use some proxy objects, like SqlAlchemy does, that will not work.

Upvotes: 5

Related Questions