简体   繁体   中英

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?

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

User.objects.filter()

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(
    
).filter()

or if you want to subtract a number:

from django.db.models import F

User.objects.annotate(
    
).filter()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM