小编典典

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

django

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

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

我想输出按月细分:

  • 一个月内有多少笔交易(COUNT
  • 合并值(SUM

我不确定最好的攻击方法是什么。我已经看到了一些看上去很吓人的额外选择查询,但我的简单想法是告诉我,最好是迭代数字,从任意开始的年/月开始,一直计数到我达到当月,然后简单地抛出查询该月的过滤条件。更多数据库工作-减轻开发人员压力!

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

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


阅读 1577

收藏
2020-03-26

共1个答案

小编典典

Django 1.10及更高版本

Django文档列表extra作为近期内取消。(感谢指出@seddonym @ Lucas03)。我打开了一张票,这就是jarshwah提供的解决方案。

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

Sales.objects
    .annotate(month=TruncMonth('timestamp'))  # 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的信息
2020-03-26