Django:未来30天每天的生日总数 [英] Django: Total birthdays each day for the next 30 days

查看:197
本文介绍了Django:未来30天每天的生日总数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似这样的模型:

I've got a model similar to this:

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

我想在未来30天内列出每一天的总生日。例如,列表将如下所示:

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 

列表中的每个列表条目都是日期编号,后面是当天的生日数。所以例如5月9日有0个生日。

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.

更新

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

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

推荐答案

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

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)

这篇关于Django:未来30天每天的生日总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆