我有
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
我知道我必须使用注释和计数,但不知道从哪里开始。
在您的示例中,我将使用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对象时,你可以这样做
person.calculate_age()
,返回值为年龄