使用django的ORM框架按月统计近一年内的数据方法 如下所示: # 计算时间 time = datetime.datetime.now() - relativedelta(years=1) # 获取近一年数据 one_year_data = Data.objects.filter(create_time__gte=time_ago) # 分组统计每个月的数据 count_res = one_year_data\ .annotate(year=ExtractYear('create_time'),month=ExtractMonth('create_time'))\ .values('year', 'month').order_by('year', 'month').annotate(count=Count('id')) print(count_res) 打印结果: annotate()方法: 对数据集先进行分组然后再进行某些聚合操作或排序时,需要使用annotate方法来实现。与aggregate方法不同的是,annotate方法返回结果的不仅仅是含有统计结果的一个字典,而是包含有新增统计字段的查询集(queryset)。 以上这篇使用django的ORM框架按月统计近一年内的数据方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持中文源码网。