[英]How to calculate if age is in range from the birth year ,while fetching the birth year from Db in Django ORM
I have a model which consists of id, name and birth year.I want to query this model to get the name such that the age is in between a range.我有一个由 id、姓名和出生年份组成的模型。我想查询这个模型以获取年龄在一个范围内的名字。
For now, what i have tried is现在,我尝试过的是
queryset= Employees.objects.all()
For each name i calculate the age by:对于每个名字,我计算年龄:
now = datetime.datetime.now()
age=now.year-q.birth_year
ids=[]
if 25<age<36 :
ids.append(q.id)
and then, i query once again with ids Employees.objects.filter(id__in=ids)然后,我再次查询 ids Employees.objects.filter(id__in=ids)
Can i do all this in a single query.我可以在一个查询中完成所有这些吗?
Employees.objects.filter(**Calculate age and compare if it is in the range)
Range can be dynamic.范围可以是动态的。 I have the range in two variable minAge and maxAge.
我有两个变量 minAge 和 maxAge 的范围。
Any help.任何帮助。
You might want to use relativedelta
from dateutil
, it's more convenient to calculate the time:你可能想使用
relativedelta
从dateutil
,它更方便地计算时间:
import datetime
from dateutil.relativedelta import relativedelta
today = datetime.date.today()
age_25 = (today - relativedelta(years=25)).year
age_36 = (today - relativedelta(years=36)).year
Employees.objects.filter(birth_year__lte=age_25, birth_year__gte=36)
age_25
is 25 years ago, age_36
is 36 years ago, you just query the people's birthdays fall between 25 and 36 years ago. age_25
是 25 年前, age_36
是 36 年前,你只是查询人们的生日在 25 到 36 年前。
For lte
and gte
check django doc for details.对于
lte
和gte
请查看django doc以了解详细信息。
Edit :编辑:
Actually, django orm supports range
query, so just do:实际上,django orm 支持
range
查询,所以只需执行以下操作:
Employees.objects.filter(birth_year__range=[age_36, age_25])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.