Django综合案例之英雄人物1
django综合案例——英雄人物的管理系统,系统分为djangoAPI 和 Vue页面文章内容为案例中的后端django流程
·
用django + Vue实现 游戏 英雄人物的管理系统,系统分为djangoAPI 和 Vue页面
django API 实现流程如下所示:
- 创建django项目,创建APP
在指定目录下cmd回车进入黑窗口:
创建django项目命令:django-admin startproject 项目名;cd 项目名进入项目;
创建APP:python manage.py startapp 应用名
(c) Microsoft Corporation。保留所有权利。
C:\Users\32976\Desktop\p5code>django-admin startproject project11
C:\Users\32976\Desktop\p5code>cd project11
C:\Users\32976\Desktop\p5code\project11>python manage.py startapp myapp
- 修改配置信息
在settings.py中修改配置信息
-
注册子应用
-
实现后端跨域
-
配置数据库
-
转换为中文(可换可不换)
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders', #跨域
'rest_framework', #drf框架
'myapp', #注册子应用
'django_filters', #过滤
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware', #关闭csrf
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware', #跨域
]
CORS_DRIGIN_ALLOW_ALL=True #允许所有源跨域
....
DATABASES = { #数据库配置
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST':'localhost',
'PORT':3306, #端口
'USER':'root',
'PASSWORD':'xxxxxxx', #密码
'NAME': 'hero', #数据库名
}
}
....
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
- 创建模型类, 注意:游戏 与 英雄人物 一对多关联
from django.db import models
# Create your models here.
class Game(models.Model):
game_name=models.CharField(max_length=20,verbose_name='游戏名称')
class Meta:
verbose_name='游戏表'
verbose_name_plural=verbose_name
db_table='game'
def __str__(self):
return self.game_name
class Hero(models.Model):
hero_name=models.CharField(max_length=20,verbose_name='英雄名')
atk=models.IntegerField(verbose_name='攻击力')
level=models.IntegerField(verbose_name='等级')
game=models.ForeignKey(Game,on_delete=models.CASCADE)
class Meta:
verbose_name='英雄表'
verbose_name_plural=verbose_name
db_table='hero'
def __str__(self):
return self.hero_name
- 添加后台管理、迁移文件、创建超级用户等
from django.contrib import admin #admin控制台
# Register your models here.
from myapp import models
admin.site.register(models.Game)
admin.site.register(models.Hero)
创建模型类命令: python manage.py makemigrations 生成迁移文件命令: python manage.py migrate 创建超级用户命令: python manage.py createsuperuser——自定义用户名——设置密码等 添加测试数据: 站点添加数据或SQL数据库添加数据
- 创建序列化器
from rest_framework import serializers
from myapp.models import Game,Hero
class GameSerializers(serializers.ModelSerializer):
class Meta:
model=Game
fields='__all__'
class HeroSerializers(serializers.ModelSerializer):
class Meta:
model=Hero
fields='__all__'
#只能序列化,不能反序列化
class HerosSerializers(serializers.ModelSerializer): #外键显示为文字
game=serializers.StringRelatedField(read_only=True)
class Meta:
model=Hero
fields='__all__'
- 创建视图,实现数据操作:增、删、改、查
from django.shortcuts import render
# Create your views here.
from rest_framework.generics import ListCreateAPIView,RetrieveUpdateDestroyAPIView
from myapp.models import Game,Hero
from myapp.serializers import GameSerializers,HeroSerializers,HerosSerializers
#过滤器
from rest_framework.viewsets import ModelViewSet
from rest_framework.filters import SearchFilter
class GameFilter(ModelViewSet):
queryset = Game.objects.all()
serializer_class = GameSerializers
filter_backends = (SearchFilter,)
search_fields= ['=game_name'] #根据游戏名查游戏信息
class HeroView(ModelViewSet):
queryset = Hero.objects.all() #英雄信息
serializer_class = HeroSerializers
from rest_framework.generics import ListAPIView
from rest_framework.filters import OrderingFilter
class HeroView2(ListAPIView):
queryset = Hero.objects.all()
serializer_class = HerosSerializers
filter_backends = (SearchFilter,OrderingFilter)
search_fields = ['game__id','game__game_name'] #游戏名或游戏id查游戏信息
ordering_fields=['level']
配置路由,提供API接口
与django项目同名的文件下的urls.py进行路由分发
from django.contrib import admin
from django.urls import path,include
from myapp import urls
urlpatterns = [
path('admin/', admin.site.urls),
path('',include(urls)),
]
子应用文件下创建urls.py配置路由
from django.urls import path
from myapp import views
from rest_framework import routers
urlpatterns = [
path('hero2/',views.HeroView2.as_view()),
]
router=routers.SimpleRouter()
router.register('game',views.GameFilter,'game')
router.register('hero',views.HeroView,'hero')
urlpatterns +=router.urls
以上为英雄人物综合案例的后端流程,下次我们继续分享vue前端流程,谢谢大家喜欢!
更多推荐
已为社区贡献2条内容
所有评论(0)