【问题标题】:Filter people from Django model using birth date使用出生日期从 Django 模型中过滤人员
【发布时间】:2014-06-15 21:24:38
【问题描述】:

我有这个模型:

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))

我该怎么做?

【问题讨论】:

    标签: python django filter date


    【解决方案1】:

    您必须检查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)
    

    【讨论】:

    • 这是一种好方法,但要在 max_date 上替换 year 时正常工作,必须将其分配给 max_date 的新值:max_date = max_date.replace(year=max_date.year - min_age) 或 max_date 将继续存储 date.today() 值。谢谢你的回答。
    • 哇,我现在感觉好蠢:/ 实际上是从我自己的源代码中提取了这个示例,用于测试...
    猜你喜欢
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 2022-12-06
    • 2021-12-08
    • 1970-01-01
    • 2011-11-16
    相关资源
    最近更新 更多