我有一个带有created
时间戳的Django模型,我想获得每天创建的对象计数。我希望在Django中使用聚合功能,但我无法弄清楚如何用它来解决我的问题。假设这不起作用我总是可以回到刚刚使用values_list获取所有日期,但我更愿意将工作交给Django或DB。你会怎么做?
答案 0 :(得分:25)
Count number of records by date in Django
积分转到ara818
Guidoism.objects.extra({'created':"date(created)"}).values('created').annotate(created_count=Count('id'))
from django.db.models import Count
Guidoism.objects \
# get specific dates (not hours for example) and store in "created"
.extra({'created':"date(created)"})
# get a values list of only "created" defined earlier
.values('created')
# annotate each day by Count of Guidoism objects
.annotate(created_count=Count('id'))
我每天都在学习新的技巧,阅读堆栈。真棒!
答案 1 :(得分:0)
使用count方法:
YourModel.objects.filter(published_on=datetime.date(2011, 4, 1)).count()