How to calculate if age is in range from the birth year ,while fetching the birth year from Db in Django ORM

馋奶兔 提交于 2019-12-19 10:21:49

问题


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.

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)

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.

Any help.


回答1:


You might want to use relativedelta from dateutil, it's more convenient to calculate the time:

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.

For lte and gte check django doc for details.

Edit:

Actually, django orm supports range query, so just do:

Employees.objects.filter(birth_year__range=[age_36, age_25])


来源:https://stackoverflow.com/questions/34772465/how-to-calculate-if-age-is-in-range-from-the-birth-year-while-fetching-the-birt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!