11

我有一个带有created时间戳的 Django 模型,我想获取每天创建的对象的数量。我希望在 Django 中使用聚合功能,但我不知道如何解决我的问题。假设这不起作用,我总是可以退回到使用 values_list 获取所有日期,但我更愿意将工作交给 Django 或 DB。你会怎么做?

4

2 回答 2

25

亚历克斯在评论中指出了正确的答案:

按日期计算 Django
Credit 中的记录数转到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'))

我每天都在学习新技巧阅读堆栈..太棒了!

于 2011-02-02T22:43:39.637 回答
0

使用计数方法:

YourModel.objects.filter(published_on=datetime.date(2011, 4, 1)).count()
于 2011-02-02T20:26:00.073 回答