python - 使用出生日期从 Django 模型中过滤人员

标签 python django filter date

我有这个模型:

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/

相关文章:

python - Django 模型 : user ID

filter - 电源 BI/DAX : Filter SUMMARIZE or GROUPBY by added column value

django - 快速问题 django 中的 : how to set *. domainname.com url

javascript - 单击模板中的按钮后如何运行 Django View 功能

list - 过滤 [Maybe a] 并丢弃 Nothing 值

python - Python 中 signal.filtfilt 中的 Padlen 错误

python - 删除 Pandas 系列中的行并清理索引

python - 分布式 Mxnet 训练中权限被拒绝

Python类找不到成员

sqlite3 中的 Python 日期时间