【问题标题】:Get daily counts of objects from Django从 Django 获取每日对象计数
【发布时间】:2011-06-20 04:48:59
【问题描述】:

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

【问题讨论】:

标签: django django-aggregation


【解决方案1】:

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'))

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

【讨论】:

【解决方案2】:

使用count 方法:

YourModel.objects.filter(published_on=datetime.date(2011, 4, 1)).count()

【讨论】:

  • 虽然每天数一数听起来有点贵
猜你喜欢
  • 2019-07-12
  • 2010-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-05
  • 2011-02-13
  • 2014-09-17
  • 1970-01-01
相关资源
最近更新 更多