【发布时间】:2011-06-20 04:48:59
【问题描述】:
我有一个带有created 时间戳的 Django 模型,我想获取每天创建的对象的数量。我希望在 Django 中使用聚合功能,但我不知道如何解决我的问题。假设这不起作用,我总是可以退回到使用 values_list 获取所有日期,但我更愿意将工作交给 Django 或 DB。你会怎么做?
【问题讨论】:
我有一个带有created 时间戳的 Django 模型,我想获取每天创建的对象的数量。我希望在 Django 中使用聚合功能,但我不知道如何解决我的问题。假设这不起作用,我总是可以退回到使用 values_list 获取所有日期,但我更愿意将工作交给 Django 或 DB。你会怎么做?
【问题讨论】:
Alex 在评论中指出了正确的答案:
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'))
我每天都在阅读堆栈学习新技巧..太棒了!
【讨论】:
extra 被列为即将弃用。现在试试TruncDay stackoverflow.com/a/8746532/2283261
使用count 方法:
YourModel.objects.filter(published_on=datetime.date(2011, 4, 1)).count()
【讨论】: