Queryset of people with a birthday in the next X days

前端 未结 6 1867
春和景丽
春和景丽 2021-01-03 13:29

how do i get queryset of people with a birthday in the next X days? I saw this answer, but it does not suit me, because gets people only with current year of birth.

6条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-03 13:59

    I have tried to do it in a really silly way, but seems it works:

    import datetime
    from django.db.models import Q
    
    x = 5
    q_args = ''
    
    for d in range(x):
        future_date = datetime.date.today() + datetime.timedelta(days=d)
        q_args += 'Q(birth_date__month=%d, birth_date__day=%d)%s' % (
            future_date.month,
            future_date.day,
            ' | ' if d < x - 1 else ''
        )
    
    people = People.objects.filter(eval(q_args))
    

提交回复
热议问题