Django:按日期分组(日、月、年)

标签 django django-aggregation

我有一个像这样的简单模型:

class Order(models.Model):
    created = model.DateTimeField(auto_now_add=True)
    total = models.IntegerField() # monetary value

我想输出以下内容的逐月分割:

  • 一个月有多少销售额(COUNT)
  • 合并值(SUM)

我不确定攻击此问题的最佳方法是什么。我已经看到了一些看起来相当可怕的额外选择查询,但我简单的想法告诉我,我可能最好只迭代数字,从任意的开始年/月开始,直到我到达当前月份,抛出简单该月的查询过滤。更多的数据库工作 - 更少的开发人员压力!

什么对您来说最有意义?有什么好的方法可以快速拉回数据表吗?或者我的肮脏方法可能是最好的主意?

我正在使用 Django 1.3。不确定他们最近是否为 GROUP_BY 添加了更好的方法。

最佳答案

Django 1.10 及以上版本

Django 文档将 extra 列为即将弃用。 (感谢@seddonym、@Lucas03 指出这一点)。我开了一个ticket这就是 jarshwah 提供的解决方案。

from django.db.models.functions import TruncMonth
from django.db.models import Count

Sales.objects
    .annotate(month=TruncMonth('created'))  # Truncate to month and add to select list
    .values('month')                          # Group By month
    .annotate(c=Count('id'))                  # Select the count of the grouping
    .values('month', 'c')                     # (might be redundant, haven't tested) select month and count 

旧版本

from django.db import connection
from django.db.models import Sum, Count

truncate_date = connection.ops.date_trunc_sql('month', 'created')
qs = Order.objects.extra({'month':truncate_date})
report = qs.values('month').annotate(Sum('total'), Count('pk')).order_by('month')

编辑

  • 添加计数
  • 为 django 添加了信息 >= 1.10

关于Django:按日期分组(日、月、年),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8746014/

相关文章:

django - 获取聚合中最大记录的 ID

python - 在 Django 中获取 'most popular' 列表

django - 如何在 Django 通用 View 中添加额外的上下文和查询集字段?

python - 在 Django 中使用元类

python - 在 Django 中按月分组并检索为 datetime.date()

python - Django 查询对 ArrayFields 的长度求和

python - 在 python 中从视频源创建视频缩略图

python - Aptana 配置 : The interpreter configured does not exist in the filesystem

python - 使用子查询注释计数

python - django queryset aggregation count 计数错误