我有
class Person(TimeStampedModel, Address):
name = models.CharField(_('nome'), max_length=100)
birthday = models.DateField(_('data de nascimento'))
和这个功能
import datetime
from datetime import date
'''
http://keyes.ie/calculate-age-with-python/
'''
def age(when, on=None):
if on is None:
on = datetime.date.today()
was_earlier = (on.month, on.day) < (when.month, when.day)
return on.year - when.year - (was_earlier)
age(date(2000, 1, 1))
如何计算每个人的年龄
age quant
20-25 89
25-30 100
30-35 90
35-40 102
我知道我必须使用annottate和count,但不知道从哪里开始。
答案 0 :(得分:0)
在你的情况下,我将使用2个函数,一个用于获取人的年龄,另一个用于准备一个返回按年龄范围分组的人的字典。
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
def get_persons_grouped_by_age():
age_dict = {
"under_20": [],
"20_25": [],
"25_30": [],
"30_35": [],
"35_40": [],
"over_40": [],
}
for person in Person.objects.all():
person_age = calculate_age(person.birthday)
if person_age < 20:
age_dict["under_20"].append(person)
if 20 <= person_age < 25:
age_dict["20_25"].append(person)
elif 25 <= person_age < 30:
age_dict["25_30"].append(person)
elif 30 <= person_age < 35:
age_dict["30_35"].append(person)
elif 35 <= person_age < 40:
age_dict["35_40"].append(person)
else:
age_dict["over_40"].append(person)
return age_dict
一个有用的提示是将calculate_age
函数作为属性添加到Person
模型中:
class Person(TimeStampedModel, Address):
name = models.CharField(_('nome'), max_length=100)
birthday = models.DateField(_('data de nascimento'))
def calculate_age(self):
today = date.today()
born = self.birthday
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
所以,当你有一个人物对象时,你可以这样做:
person.calculate_age()
并且回报将是年龄