我有这个模型:
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))
我怎样才能做到这一点?
最佳答案
您必须对照最大允许生日的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)
关于python - 使用出生日期从Django模型中过滤人,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23373151/