使用django的ORM框架按月统计近一年内的数据方法

yipeiwu_com6年前Python基础

如下所示:

# 计算时间
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框架按月统计近一年内的数据方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

解决django前后端分离csrf验证的问题

第一种方式ensure_csrf_cookie 这种方方式使用ensure_csrf_cookie 装饰器实现,且前端页面由浏览器发送视图请求,在视图中使用render渲染模板,响应给前...

python Socket之客户端和服务端握手详解

python Socket之客户端和服务端握手详解

简单的学习下利用socket来建立客户端和服务端之间的连接并且发送数据 1. 客户端socketClient.py代码 import socket s = socket.soc...

基于python历史天气采集的分析

基于python历史天气采集的分析

分析历史天气的趋势。 先采集 代码: #-*- coding:utf-8 -*- import requests import random import MySQLdb im...

linux环境下python中MySQLdb模块的安装方法

前言 最近开始学习python数据库编程后,在了解了基本概念,打算上手试验一下时,卡在了MYSQLdb包的安装上,折腾了半天才解决。记录一下我在linux中安装此包遇到的问题。 系统是u...

Python2和Python3中print的用法示例总结

前言 最近在学习python,对于python的print一直很恼火,老是不按照预期输出。在python2中print是一种输出语句,和if语句,while语句一样的东西,在python...