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 queryse
Solution 1:
You might want to use relativedelta
from dateutil
, it's more convenient to calculate the time:
import datetime
from dateutil.relativedelta importrelativedeltatoday= datetime.date.today()
age_25 = (today - relativedelta(years=25)).yearage_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])
Post a Comment for "How To Calculate If Age Is In Range From The Birth Year ,while Fetching The Birth Year From Db In Django Orm"