我有这个型号:
class People(models.Model):
"""
People model
"""
name = models.CharField(max_length=120)
birth_date = models.DateField()
我希望过滤所有年龄为参数的人,例如:
min_age = 24
# Filter people older than ´min_age´
people = People.objects.filter(birth_date__lte = (#something here to filter with age))
我该怎么做?
答案 0 :(得分:2)
您必须检查允许的最大出生日期datetime.date
:在那天之后出生的人将比最小年龄小:
from datetime import date
min_age = 24
max_date = date.today()
try:
max_date = max_date.replace(year=max_date.year - min_age)
except ValueError: # 29th of february and not a leap year
assert max_date.month == 2 and max_date.day == 29
max_date = max_date.replace(year=max_date.year - min_age, month=2, day=28)
people = People.objects.filter(birth_date__lte=max_date)