How to filter a query on Django ORM

Anibal Cardozo

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?

Willem Van Onsem

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.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Django ORM grouped by query

分類Dev

How do I do date math in a Django ORM query?

分類Dev

Django - How to query a list inside of a filter method

分類Dev

How to convert this query to the Peewee ORM?

分類Dev

Query Django ORM with foreign key fields

分類Dev

How do I write a Django ORM query for the reverse relationship in a one-to-many relationship?

分類Dev

Filter nested query if no results in Django

分類Dev

How to filter a query set

分類Dev

How to convert sql mod to django orm?

分類Dev

How to connect Django ORM to mongo atlas?

分類Dev

Django query filter many to many to many etc

分類Dev

to access the filter query result passed to templates in django

分類Dev

how to filter WP_Query

分類Dev

How to store emoji string in Database using Laravel with Orm Query

分類Dev

How to describe One To One relationships from Django ORM in SqlAlchemy?

分類Dev

How to filter out from count distinct query

分類Dev

Django: Fastest way to random query one record using filter

分類Dev

Django & Mongo ORM mapping

分類Dev

django orm JSONField for mysql

分類Dev

Django ORM INNER JOIN

分類Dev

How to get filter key and result tuple in Django

分類Dev

How to create a correct filter string with OR and AND operators for django?

分類Dev

How to filter objects for django admin panel?

分類Dev

Django ORM-objects.filter()とobjects.all()。filter()-どちらが望ましいですか?

分類Dev

Two way table and django ORM

分類Dev

How to reverse query objects for multiple levels in django?

分類Dev

How to print the query of .get queryset in django

分類Dev

Django how to see generated SQL query?

分類Dev

Django Query: How to order posts by amount of upvotes?

Related 関連記事

ホットタグ

アーカイブ