Getting upcoming birthdays using 'date of birth' DateField

前端 未结 3 1655
醉梦人生
醉梦人生 2021-01-26 17:24

I\'m trying to get the birthdays in the upcoming 20 days, given the below Person model:

class Person(models.Model):
    dob = models.DateField()  #          


        
3条回答
  •  温柔的废话
    2021-01-26 18:06

    FYI, I ended up doing the following which works for me and which does not require raw SQL. Any improvements would be welcomed :-)

    # Get the upcoming birthdays in a list (which is ordered) for the amount of days specified
    def get_upcoming_birthdays(person_list, days):
        person_list= person_list.distinct()  # ensure persons are only in the list once
        today = date.today()
        doblist = []
        doblist.extend(list(person_list.filter(dob__month=today.month, dob__day=today.day)))
        next_day = today + timedelta(days=1)
        for day in range(0, days):
            doblist.extend(list(person_list.filter(dob__month=next_day.month, dob__day=next_day.day, dod__isnull=True)))
            next_day = next_day + timedelta(days=1)
        return doblist
    

提交回复
热议问题