Django: Total birthdays each day for the next 30 days

后端 未结 4 942
遇见更好的自我
遇见更好的自我 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:08
    from django.db.models import Count
    import datetime
    today = datetime.date.today()
    thirty_days = today + datetime.timedelta(days=30)
    birthdays = dict(Person.objects.filter(
                        birthday__range=[today, thirty_days]
                     ).values_list('birthday').annotate(Count('birthday')))
    
    
    for day in range(30):
        date = today + datetime.timedelta(day)
        print "[%s, %s]" % (date, birthdays.get(date, 0))
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2021-01-03 17:13

    Something like this --

    from datetime import date, timedelta
    
    class Person(models.Model):
        name = models.CharField(max_length=40)
        birthday = models.DateField()
    
        @staticmethod
        def upcoming_birthdays(days=30):
            today = date.today()
            where = 'DATE_ADD(birthday, INTERVAL (YEAR(NOW()) - YEAR(birthday)) YEAR) BETWEEN DATE(NOW()) AND DATE_ADD(NOW(), INTERVAL %S DAY)'
            birthdays = Person.objects.extra(where=where, params=[days]).values_list('birthday', flat=True)
            data = []
            for offset in range(0, days):
                i = 0
                d = today + timedelta(days=offset)
                for b in birthdays:
                    if b.day == d.day and b.month == d.month:
                        i += 1
                data.append((d.day, i))
            return data
    
    print Person.upcoming_birthdays()
    
    0 讨论(0)
  • 2021-01-03 17:24

    (Queryset of people with a birthday in the next X days) Found cool solution for this! For me it works!

    from datetime import datetime, timedelta
    import operator
    
    from django.db.models import Q
    
    def birthdays_within(days):
    
        now = datetime.now()
        then = now + timedelta(days)
    
        # Build the list of month/day tuples.
        monthdays = [(now.month, now.day)]
        while now <= then:
            monthdays.append((now.month, now.day))
            now += timedelta(days=1)
    
        # Tranform each into queryset keyword args.
        monthdays = (dict(zip(("birthday__month", "birthday__day"), t)) 
                     for t in monthdays)
    
    
        # Compose the djano.db.models.Q objects together for a single query.
        query = reduce(operator.or_, (Q(**d) for d in monthdays))
    
        # Run the query.
        return Person.objects.filter(query)
    

    But it get a list of persons that have a birthday in date range. You should change a bit.

    0 讨论(0)
提交回复
热议问题