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:大功告成,訪問路由,展示

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM