Django: Total birthdays each day for the next 30 days

后端 未结 4 965
遇见更好的自我
遇见更好的自我 2021-01-03 16:35

I\'ve got a model similar to this:

class Person(models.Model):
    name = models.CharField(max_length=40)
    birthday = DateTimeField() # their next birthda         


        
4条回答
  •  天命终不由人
    2021-01-03 17:11

    I would get the list of days and birthday count this way:

    from datetime import date, timedelta    
    today = date.today()
    thirty_days = today + timedelta(days=30)
    
    # get everyone with a birthday
    people = Person.objects.filter(birthday__range=[today, thirty_days])
    
    birthday_counts = []
    for date in [today + timedelta(x) for x in range(30)]:
        # use filter to get only birthdays on given date's day, use len to get total
        birthdays = [date.day, len(filter(lambda x: x.birthday.day == date.day, people))]
        birthday_counts.append(birthdays)
    

提交回复
热议问题