1.1:新建項目html
django-admin startproject Test
1.2:新建apppython
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:建立數據庫模型,因爲只是示例,因此簡單點django
# 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後臺很方便,因此就配置下adminsession
# 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:遷移、生成數據表,建立管理員帳戶app
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
1.7:運行項目,進入後臺添加數據echarts
python manage.py runserver
如下是我添加的數據,總共6條,1條2月,5條3月url
2.1:編輯 views.py spa
# 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.pydebug
# 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:大功告成,訪問路由,展現