1

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?

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I simplified the problem to make it easier to understand, but can I do opperations inside the filter? something like User((age__ - aux)lt=18) ? I need to know if the age minus X number is still < 18
@AnibalCardozo: then you usually make .annotate(..)s and filter on these: docs.djangoproject.com/en/3.0/ref/models/querysets/#annotate
I see what you mean, annotate seems to be the answer, but I still have a problem I get an error when using the attribute if put something like this User.objects.annotate(age - X < 18) I get an error with "name 'age' is not defined" If I try Users.objects.annotate ('age' - X < 18) I get an error like "unsupported operand type(s) for -: 'str' and 'int'"
@AnibalCardozo: but for the same reasons as listed in the answer for filtering, you can not do this for annotation. See the edited answer for some examples on how to annotate.
I figured it out a solution for my specific case, the answer was actually a lot simpler, instead of doing the operation inside the filter I could do it outside, something like this ``` real_age = X+18 User.objects.filter(age__lt=real_age) ```

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.