Django rest Framework 跑通流程总结
昨天跟着王进老师学了V5版本的前后分离,特此记录一下DRF跑通全流程
1. 安装配置环境
1.1 pycharm中新建立一个Django
因我们使用DRF,不需要Template功能,所以Templates folder这里置空
1.2 测试是否安装成功
运行 python manage.py runserver 看看Django是否安装成功 3. 停止掉当前terminal终端,并执行pip install djangorestframework pymysql 安装好DRF和mysql包 4. 执行 python manage.py startapp stu 创建一个名为stu的app 5. 新建一个apps的目录,并将apps设置为Sources Root,将stu目录拖到apps里去
2. 开始注册app和映射路由
2.1 注册apps
apps所在目录注册(不注册的话django不能识别此目录) 注册app
2.2 url路由映射
在stu中新建立一个urls将刚新建的stu.urls映射到根路由
3. 配置数据库连接
3.1 手动先创建一个mysql数据库
3.2 配置mysql连接信息
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'stu_db',
'USER': 'root',
'PASSWORD': '12345.Com',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
3.2 在__init__.py 导入mysql
import pymysql
pymysql.install_as_MySQLdb()
4. 代码部分
4.1 编写stu.models代码
from django.db import models
class Faculty(models.Model):
name = models.CharField(verbose_name='学院名称', max_length=100, unique=True, null=False, blank=False)
class Meta:
managed = True
app_label = 'stu'
db_table = 'stu_faculty'
def __str__(self):
return '%s' % (self.name)
class Major(models.Model):
name = models.CharField(verbose_name='专业名称', max_length=100, null=False, blank=False)
faculty = models.ForeignKey(verbose_name='所属学院', to=Faculty,on_delete=models.PROTECT)
class Meta:
managed = True
app_label = 'stu'
db_table = 'stu_major'
def __str__(self):
return '%s' % (self.name)
class Student(models.Model):
sno = models.CharField(verbose_name='学号', max_length=100, primary_key=True, null=False, blank=False)
name = models.CharField(verbose_name='姓名', max_length=100, null=False, blank=False)
gender = models.CharField(verbose_name='性别', max_length=100, null=True, blank=True, default=None)
birthday = models.DateField(verbose_name='出生日期', null=True, blank=True, default=None)
major = models.ForeignKey(verbose_name='专业', to=Major, on_delete=models.PROTECT)
mobile = models.CharField(verbose_name='电话', max_length=100, null=True, blank=True, default=None)
email = models.CharField(verbose_name='邮箱', max_length=100, null=True, blank=True, default=None)
address = models.CharField(verbose_name='地址', max_length=100, null=True, blank=True, default=None)
image = models.CharField(verbose_name='照片', max_length=100, null=True, blank=True, default=None)
class Meta:
managed = True
app_label = 'stu'
db_table = 'stu_student'
def __str__(self):
return '%s' % (self.name)
具体模型化的字段类型和相应的属性一共有哪些我也还没学完, 看字面意思models.CharField 是字符串类型,models.DateField 是日期类型,models.ForeignKey 是外键 其中属性max_length=100 是最大长度,primary_key=True 主键,null=False 不能为null,blank=False 不能为空,default=None 默认值
4.2 序列化模型
在stu中建立一个serializer.py并写入如下代码,此处serializer.py只是大家约定约定熟成的名称
from rest_framework import serializers
from stu.models import Faculty, Major, Student
class FacultySerializer(serializers.ModelSerializer):
class Meta:
model = Faculty
fields = '__all__'
class MajorSerializer(serializers.ModelSerializer):
class Meta:
model = Major
fields = '__all__'
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = '__all__'
如图:
4.3 书写视图
写视图
from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from stu.models import Faculty, Major, Student
from stu.serializer import FacultySerializer, MajorSerializer, StudentSerializer
class FacultyViewSet(ModelViewSet):
queryset = Faculty.objects.all()
serializer_class = FacultySerializer
class MajorViewSet(ModelViewSet):
queryset = Major.objects.all()
serializer_class = MajorSerializer
class StudentViewSet(ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializer
4.4 从模型到数据库
4.4.1 生成数据库迁移文件
运行python manage.py makemigrations 生成数据库迁移文件
4.4.2 模型同步到数据库
运行python manage.py migrate 将生成的数据库迁移文件迁移到数据库 去数据库中查看我们会发现生成了一系列表,其中有三张就是我们模型化得来的
4.4.3 在数据库中添加一些测试数据
在stu_faculty学院表中添加测试数据 在stu_major专业表中添加测试数据
5. 程序跑起来
运行python manage.py runserver 把程序跑起来 访问我们刚才urls里配置路径 http://127.0.0.1:8000/stu/v1/ 在http://127.0.0.1:8000/stu/v1/facultys/ 里就是我们的学院信息
要查单独一条学院信息就是http://127.0.0.1:8000/stu/v1/facultys/{id值} ,如: 查找专业 查找学生发现没记录(我们本来在数据库中就没添加记录) 添加一个学生记录,添加后就有学生相应信息了
6. 总结一下知识点
跑通的整个过程回顾 创建Django项目—>创建app—>app路由映射—>配置数据库—>写数据库模型—>序列化数据库模型—>写视图—>迁移—>跑起来…
pip install pymysql djangorestframework
python manage.py startapp appname
创建一个apps python包 将appname目录移动到apps setting.py中配置数据库,注册apps目录,注册app
models.py建立数据模型
from django.db import models
class Student(models.Model): 继承
name = models.CharField(verbose_name='姓名', max_length=20, null=False, blank=False)
...
...
birthday = models.DateField(verbose_name='出生日期', max_length=20, null=True, blank=True)
class Meta:
managed = True
app_label = 'myapp'
db_table = 'tb_student'
def __str__(self):
return '%s' % (self.name)
python manage.py makemigrations
python manage.py migrate
serializer models 将模型序列化 建立一个serializer.py
from rest_framework import serializer
from appname.models import Student
class StudentSerializer(serializer.ModelSerializer):
class Meta:
model = Student
fields = "__all__"
创建视图views.py
from rest_framework.views import ModelViewSet
from appname.models import Student
from appname.serializer import StudentSerializer
class StudentViewSet(ModelViewSet):
queryset = Student.object.all()
serializer_class = StudentSerializer
创建appname/urls.py 在项目urls.py中建立包含app中urls
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/', include('appname.urls')),
from rest_framework.routers import DefaultRouter
from appname.views import StudentViewSet
router = DefaultRouter()
router.register('', StudentViewSet, basename='')
urlpatterns = []
urlpatterns += router.urls
|