python - How to calculate user age from birth year till registration date using Django ORM -
i have model contains field birth_year , in model have user registration date. have list of user ids want query if age belongs particular range of age.user age calculated registration date - birth_year.
i able calculate current date as:
startage=25 endage=50 agestartrange = (today - relativedelta(years=startage)).year ageendrange = (today - relativedelta(years=endage)).year
and made query as:
query.filter(profile_id__in=communityusersids, birth_year__lte=age_from, birth_year__gte=age_to).values('profile_id')
this way getting userids age in range bw 25 , 50. instead of today how can use registration_date(it field in model) of user.
the "today" version of query easy do, because "today" date doesn't depend on individual fields in row.
f expressions
you can explore django's f expressions allow reference fields of model in queries (without pulling them python)
https://docs.djangoproject.com/en/1.7/topics/db/queries/#using-f-expressions-in-filters
e.g. you, age f expressions:
f('registration_date__year') - f('birth_year')
however, don't really need calculate that, because e.g. query want, consider query:
model.filter(birth_year__lte=f('regisration_date__year') - 25)
from can add a:
birth_year__gte=f('regisration_date__year') + 50
,
or use birth_year__range=(f('regisration_date__year') - 25, f('regisration_date__year') + 50))
alternative: precalculate age value
otherwise can precalculate age, since value knowable on user registration time
model.update(age=f('registration_date__year') - f('birth_year'))
once saved, it's simple model.filter(age__range=(25, 50))
Comments
Post a Comment