使用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)
打印结果:
<QuerySet [{'year': 2018, 'month': 7, 'count': 3}, {'year': 2019, 'month': 5, 'count': 7}, {'year': 2019, 'month': 6, 'count': 161}]>
annotate()方法:
对数据集先进行分组然后再进行某些聚合操作或排序时,需要使用annotate方法来实现。与aggregate方法不同的是,annotate方法返回结果的不仅仅是含有统计结果的一个字典,而是包含有新增统计字段的查询集(queryset)。
以上这篇使用django的ORM框架按月统计近一年内的数据方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。