django ORM 按月分组统计
一、搭建环境,准备数据
1.1:新建项目
django-admin startproject Test
1.2:新建app
python manage.py startapp app
1.3:设置 settings.py
# settings.py # 允许访问的ip地址 ALLOWED_HOSTS = ['*'] # 把app添加到 INSTALLED_APPS 中 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', ] # 配置静态文件存放地址,然后在对应位置新建文件夹,由于我的django版本是3.x,所以路径是这种写法 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
1.4:创建数据库模型,由于只是示例,所以简单点
# models.py from django.db import models # Create your models here. class AppModel(models.Model): name = models.CharField(max_length=20) date = models.DateField() def __str__(self): return self.name
1.5:因为要添加数据,感觉用admin后台很方便,所以就配置下admin
# admin.py from django.contrib import admin from app.models import AppModel # Register your models here. @admin.register(AppModel) class AppAdmin(admin.ModelAdmin):
list_display = ['name', 'date']
1.6:迁移、生成数据表,创建管理员账户
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
1.7:运行项目,进入后台添加数据
python manage.py runserver
以下是我添加的数据,总共6条,1条2月,5条3月
二、现在就是重点了,使用ORM按月分组,并统计每月的数量,然后以图表的形式展示出来(这样只是为了更直观)
2.1:编辑 views.py
# views.py from django.shortcuts import render from django.views import View from django.db.models.functions import ExtractMonth from django.db.models import Count from app.models import AppModelfrom pyecharts.charts import Bar # Create your views here. class AppView(View): def get(self, request):
# ORM 实现 按月分组进行统计 data = AppModel.objects.annotate(month=ExtractMonth('date')).values('month').annotate(num=Count('name')) # 图表展示 bar = Bar() bar.add_xaxis([f"{i['month']}月" for i in data]) bar.add_yaxis('每月离职人数统计表', [i['num'] for i in data]) bar.render('templates/render.html') return render(request, 'render.html')
2.2:配置路由 Test/urls.py
# urls.py from django.contrib import admin from django.urls import path from app import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.AppView.as_view()), ]
2.3:大功告成,访问路由,展示