Django:接下来 30 天每天的生日总数

发布于 2024-11-05 14:24:11 字数 434 浏览 0 评论 0原文

我有一个与此类似的模型:

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

我想获取接下来 30 天每天的生日总数列表。例如,该列表将如下所示:

[[9, 0], [10, 3], [11, 1], [12, 1], [13, 5], ... #30 entries in list 

列表中的每个列表条目都是一个日期数字,后跟该天的生日数。例如,5 月 9 日有 0 个生日。

更新

我的数据库是 sqlite3 - 将来将转移到 postgres。

I've got a model similar to this:

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

I would like to get a list of the total birthdays for each day for the next 30 days. So for example, the list would look like this:

[[9, 0], [10, 3], [11, 1], [12, 1], [13, 5], ... #30 entries in list 

Each list entry in the list is a date number followed by the number of birthdays on that day. So for example on the 9th of May there are 0 birthdays.

UPDATES

My db is sqlite3 - will be moving to postgres in the future.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

緦唸λ蓇 2024-11-12 14:24:11
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))
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))
寂寞笑我太脆弱 2024-11-12 14:24:11

我会这样得到天数和生日计数的列表:

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)

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)
人│生佛魔见 2024-11-12 14:24:11

像这样的事情——

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()

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()
岁月染过的梦 2024-11-12 14:24:11

(未来 X 天内生日的人的查询集)
找到了很酷的解决方案!
对我来说它有效!

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)

但它得到了生日在日期范围内的人员列表。你应该改变一点。

(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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文