且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2021-12-16 22:00:01

Django 1.10 及更高版本

Django 文档将 extra 列为即将弃用.(感谢您指出 @seddonym、@Lucas03).我打开了一张 ticket,这是 jarshwah 提供的解决方案.

Django documentation lists extra as deprecated soon. (Thanks for pointing that out @seddonym, @Lucas03). I opened a ticket and this is the solution that jarshwah provided.

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 添加了信息