How to calculate if age is in range from the birth year ,while fetching the birth year from Db in Django ORM

前端 未结 1 1439
耶瑟儿~
耶瑟儿~ 2021-01-15 01:28

I have a model which consists of id, name and birth year.I want to query this model to get the name such that the age is in between a range.

For now, what i have tr

相关标签:
1条回答
  • 2021-01-15 02:00

    You might want to use relativedelta from dateutil, it's more convenient to calculate the time:

    import datetime
    from dateutil.relativedelta import relativedelta
    
    today = datetime.date.today()
    age_25 = (today - relativedelta(years=25)).year
    age_36 = (today - relativedelta(years=36)).year
    Employees.objects.filter(birth_year__lte=age_25, birth_year__gte=36)
    

    age_25 is 25 years ago, age_36 is 36 years ago, you just query the people's birthdays fall between 25 and 36 years ago.

    For lte and gte check django doc for details.

    Edit:

    Actually, django orm supports range query, so just do:

    Employees.objects.filter(birth_year__range=[age_36, age_25])
    
    0 讨论(0)
提交回复
热议问题