作用:大量缩减编写api接口代码
思路:
安装教程
1.安装django
2.安装djangorestframework
3.django的settings.py中注册'rest_framework'
使用教程:
- 创建模型类:数据库链接 ,并且建立好数据库模型(Student)
-
from django.db import models class Student(models.Model): """学生模型""" name = models.CharField(max_length=100, verbose_name="姓名") sex = models.BooleanField(default=1, verbose_name="性别") age = models.IntegerField(verbose_name="年龄") class_null = models.CharField(max_length=5, verbose_name="班级编号") description = models.TextField(max_length=1000, verbose_name="个性签名") class Mate: db_table = 'tb_student' verbose_name = '学生' verbose_name_plural = verbose_name
- 创建序列化器:创建serializers.py:将数据库模型序列化,创建出序列化器
from rest_framework import serializers # 导入序列化器基类(2个) from FRAMEWORK.models import Student # 序列化基类 # serializers.Serializers # serializers.ModelSerializers class StudentModelSerializers(serializers.ModelSerializer): # 指定序列化模型 class Meta: model = Student fields = "__all__" # 全部字段 # fields=['id',"name"]部分字段
- 编写视图:Student视图:创建ViewSet
-
from rest_framework.viewsets import ModelViewSet from FRAMEWORK.models import Student from FRAMEWORK.serializers import StudentModelSerializers class StudentModelViewSet(ModelViewSet): queryset = Student.objects.all() # 指明视图集在查询数据时使用的查询集 serializer_class = StudentModelSerializers # 指定序列化器或者反序列化器
- 定义路由:urls.py路由:自动生成路由
-
from django.urls import re_path, path from FRAMEWORK.views import Student, Test from FRAMEWORK.views.Student import StudentModelViewSet from rest_framework.routers import SimpleRouter, DefaultRouter # 自动生成路由模块(2选1即可) urlpatterns = [ # 测试页 path(r'test', Test.test, name='test'), ] # 学生api """ router.register("前缀(用于区分api接口)",viewset=指定序列化模型视图,basename=别名) """ router = DefaultRouter() # 实例化路由生成器 router.register('stu', viewset=StudentModelViewSet, basename="stu") # 生成5个路由 urlpatterns += router.urls
- 运行测试
-