django - Getting upcoming birthdays using 'date of birth' DateField -
i'm trying birthdays in upcoming 20 days, given below person model:
class person(models.model): dob = models.datefield() # date of birth there similar questions on (here , here), these not cover use case, i'm storing date of birth instead of next birthday or timefield.
i've tried things following:
from datetime import timedelta, date today = date.today() next_20_days = today+timedelta(days=20) person.objects.filter(dob__month=today.month, dob__day__range=[today.day, next_20_days.day]) ... fielderror: unsupported lookup 'day' datefield or join on field not permitted.
when e.g. person.objects.filter(dob__month=today.month, dob__day=next_20_days.day), results 20 days now. potentially go on each of 20 days in loop, seems rather ineffective.
any idea on how proper way?
fyi, ended doing following works me , not require raw sql. improvements welcomed :-)
# upcoming birthdays in list (which ordered) amount of days specified def get_upcoming_birthdays(person_list, days): person_list= person_list.distinct() # ensure persons in 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) 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
Comments
Post a Comment