DRF 一对多序列化与反序列化

Posted wuxiaoshi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DRF 一对多序列化与反序列化相关的知识,希望对你有一定的参考价值。

DRF 一对多序列化与反序列化

  • 序列化

    出库的过程,是从数据库中把数据读出并以json的形式供前端使用

  • 反序列化

    入库的过程,是从前端将数据传入到views.py的函数或者类中,经过后台逻辑处理,最终写到数据库中。

  • 安装 djangorestframework

    pip install djangorestframework

  • 注册到INSTALL_APPS

    INSTALLED_APPS = [
        ...
        'rest_framework',
    ]
  • 配置数据库

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'tutorial',
            'HOST': '127.0.0.1',
            'PORT': 3306,
            'USER': 'root',
            'PASSWORD': 'ocnt-123',
            'OPTIONS':{
                    "init_command":"SET foreign_key_checks = 0;",# 禁用外键约束
            }
        }
    }
  • 新增老师类和学生类

from django.db import models

# 创建老师模型
class Teacher(models.Model):
    # 教师名称
    name = models.CharField(max_length=32,unique=True)
    # 添加时间
    addtime = models.DateTimeField(auto_now_add=True)

    class Meta:
        # 指定表名
        db_table = 'teacher'


# 创建学生模型,一个学生只能选择一个老师
class Student(models.Model):
    # 学生名称
    name = models.CharField(max_length=32,unique=True)
    # 添加时间
    addtime = models.DateTimeField(auto_now_add=True)
    # 外键 与Teacher类绑定
    teacher = models.ForeignKey('Teacher',on_delete=models.CASCADE)

    class Meta:
        # 指定表名
        db_table = 'student'
  • 新增视图函数类 TeacherView

    from rest_framework.views import  APIView
    from rest_framework.response import Response
    from .serializers import TeacherSerializer,StudentSerializer
    from . import models
    
    # 创建用户视图类
    class TeacherView(APIView):
        # 获取用户信息
        def get(self,request):
            data = models.Teacher.objects.all()
            info = TeacherSerializer(data,many=True)
            return Response({
                "status":200,
                "msg":"",
                "data":info.data
            })
    
    
    
        # 添加用户
        def post(self,request):
            data = request.data
            flag = models.Teacher.objects.create(**data)
            if not flag:
                return Response({"status":201,"msg":"添加数据失败","data":[]})
            return Response({"status":200,"msg":"","data":[]})
    
    
    
        # 编辑用户
        def put(self,request):
            id = request.data.pop("id")
            flag = models.Teacher.objects.filter(id=id).update(**request.data)
            if not flag:
                return Response({
                    "status":201,
                    "msg":"编辑失败",
                    "data":[]
                })
            return Response({
                "status":200,
                "msg":"编辑成功",
                "data":""
            })
    
    
        # 删除用户
        def delete(self,request):
            id = request.data.pop('id')
            teacher = models.Teacher.objects.filter(id=id).delete()
            if not teacher[0]:
                return Response({
                    "status": 201,
                    "msg": "删除失败",
                    "data": []
                })
            return Response({
                "status": 200,
                "msg": "删除成功",
                "data": ""
            })
    
    • 新增视图函数类 StudentView
    # 学生视图
    class StudentView(APIView):
        # 获取数据
        def get(self,request):
            data = models.Student.objects.all()
            info = StudentSerializer(data,many=True)
    
            return Response({
                "status":200,
                "msg":"",
                "data":info.data
            })
    
        # 添加数据
        def post(self,request):
            data = request.data
            flag = models.Student.objects.create(**data)
            if not flag:
                return Response({
                    "status":201,
                    "msg":"学生添加失败",
                    "data":[]
                })
            return Response({
                "status":200,
                "msg":"学生添加成功",
                "data":[]
            })
    
    
        # 编辑数据
        def put(self,request):
            id = request.data.pop('id')
            flag = models.Student.objects.filter(id=id).update(**request.data)
            if not flag:
                return Response({
                    "status":201,
                    "msg":"数据编辑失败",
                    "data":[]
                })
            return Response({
                "status":200,
                "msg":"数据编辑成功",
                "data":[]
            })
    
        # 删除数据
        def delete(self,request):
            id = request.data.get('id')
            student = models.Student.objects.filter(id=id).delete()
            if not student[0]:
                return Response({
                    "status":201,
                    "msg":"删除失败",
                    "data":[]
                })
            return Response({
                "status":200,
                "msg":"删除成功",
                "data":[]
            })
    
  • 序列化类 serializers.py

    from rest_framework import serializers
    from . import models
    
    # 老师数据序列化
    class TeacherSerializer(serializers.ModelSerializer):
        class Meta:
            model = models.Teacher
            fields = '__all__'
    
    
    # 学生数据序列化
    class StudentSerializer(serializers.ModelSerializer):
        class Meta:
            model = models.Student
            fields = '__all__'
    
  • 二级路由 urls.py

    from django.urls import path
    from . import views
    urlpatterns = [
        path('teacher/',views.TeacherView.as_view()),
        path('student/',views.StudentView.as_view()),
    ]
  • 访问地址

    • GET http://127.0.0.1:8000/snippets/teacher/
      技术图片
    • POST http://127.0.0.1:8000/snippets/teacher/
      技术图片
    • PUT http://127.0.0.1:8000/snippets/teacher/
      技术图片
    • DELETE http://127.0.0.1:8000/snippets/teacher/
      技术图片

    • GET http://127.0.0.1:8000/snippets/student/
      技术图片
    • POST http://127.0.0.1:8000/snippets/student/
      技术图片
    • PUT http://127.0.0.1:8000/snippets/student/
      技术图片
    • DELETE http://127.0.0.1:8000/snippets/student/
      技术图片

  • 获取老师名下有多少个学生

    • serializers.py

      from rest_framework import serializers
      from . import models
      
      # 学生数据序列化
      class StudentSerializer(serializers.ModelSerializer):
          class Meta:
              model = models.Student
              fields = '__all__'
      
      
      # 老师数据序列化
      class TeacherSerializer(serializers.Serializer):
          id = serializers.IntegerField()
          name = serializers.CharField(max_length=32)
          student_set = StudentSerializer(many=True,read_only=True)
    • 调用此地址 GET http://127.0.0.1:8000/snippets/teacher/
      技术图片

  • 获取学生的老师是谁?

    • serializers.py

      from rest_framework import serializers
      from . import models
      
      # 学生数据序列化
      class StudentSerializer(serializers.ModelSerializer):
          teacherName = serializers.CharField(source='teacher.name')
          class Meta:
              model = models.Student
              fields = ('id','name','teacherName')
      
      
      # 老师数据序列化
      class TeacherSerializer(serializers.Serializer):
          id = serializers.IntegerField()
          name = serializers.CharField(max_length=32)
          student_set = StudentSerializer(many=True,read_only=True)
    • 调用此地址 GET http://127.0.0.1:8000/snippets/teacher/
      技术图片

以上是关于DRF 一对多序列化与反序列化的主要内容,如果未能解决你的问题,请参考以下文章

drf序列化器与反序列化

drf序列化与反序列化

drf框架2-序列化与反序列化

drf框架序列化

内部类,drf响应类,序列化与反序列化

drf--ModelSerializers序列化