Queryset of people with a birthday in the next X days

前端 未结 6 1851
春和景丽
春和景丽 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 14:09

    I can think of 2 ways without using custom queries, both with "problems"

    1) Not efficient as it does 1 query per day

    start = datetime.date.today()
    max_days = 14
    days = [ start + datetime.timedelta(days=i) for i in xrange(0, max_days) ]
    
    birthdays = []
    for d in days:
        for p in Profile.objects.filter(birthday__month=d.month, birthday__day=d.day):
            birthdays.append(p)
    
    print birthdays
    

    2) Single query, but requires a model change. You would need to add bday_month and bday_day integer fields. These can obviously be populated automatically from the real date.

    The limitation of this example is that you can only check against 2 months, start month and the end month. Setting 29 days you could jump over february, showing only Jan 31 and Mar 1.

    from django.db.models import Q    
    start = datetime.date.today()
    end = start + datetime.timedelta(days=14)
    
    print Profile.objects.filter(
        Q(bday_month=start.month) & Q(bday_day__gte=start.day) | 
        Q(bday_month=end.month) & Q(bday_day__lte=end.day)
    )
    

提交回复
热议问题