您好我正在编写一个Django应用程序,该应用程序报告所购买的每日商品。 我想在字典结构中组织数据,如此..
monthly_items = {
"Apr-27" : [ list of objects purchased on April-27th ]
"Apr-26" : [ list of objects purchased on April-26th ]
"Apr-25" : [ list of objects purchased on April-25th ]
"Apr-24" : [ list of objects purchased on April-24th ]
...
"Mar-27" : [ list of objects purchased on March-27th ]
}
现在我的代码看起来像这样(start_date和end_date分别为上个月和今天配置):
month_dict = {
1: 'Jan',
2: 'Feb',
3: 'Mar',
4: 'Apr',
5: 'May',
6: 'June',
7: 'July',
8: 'Aug',
9: 'Sept',
10: 'Oct',
11: 'Nov',
12: 'Dec',
}
from collections import OrderedDict
monthly_items = OrderedDict()
# pull items from last 30 days
items = Item.objects.filter(create_date__gte=start_date, create_date__lt=end_date).order_by('-create_date')
for item in items:
day = str(month_dict.get(item.create_date.month)) + '-' + str(item.create_date.day)
day_items = monthly_items.get(day, [])
day_items.append(item)
这很好用,我得到了我想要的字典结构,但我的问题是如果4月24日没有购买任何商品,字典中就没有关键字了,当我打印我的字典到html时,我错过了4月24日专栏,实际上,我想要一个但是有一个空列表。有没有办法预先填充最近30天的有序字典作为键(兼容跨月)?