简体   繁体   中英

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.

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.

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])

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