多对多反序列化案例

  • 创建一个经典的多对多关系:一个学生可以有多个老师,一个老师可以有个学生

    from django.db import models
    
    # 学生类
    class Student(models.Model):
        name = models.CharField(max_length=32)
    
        # 老师类
    class Teacher(models.Model):
        name = models.CharField(max_length=32)
        stu = models.ManyToManyField(to='Student',related_name='teacher')
    
  • 进行数据迁移

    python manage.py makemigrations
    python manage.py migrate
    
  • 查看表结构

    • app04_student 学生表
    • app04_teacher 老师表
    • app04_teacher_stu 中间表
  • 创建序列化文件

    from rest_framework import serializers
    from . import models
    # 反序列化
    class TeacherUnserializer(serializers.Serializer):
        # required = False 可以传值,也可以不传值
        id = serializers.IntegerField(required=False)
        student_id = serializers.ListField()
    
        # 添加
        def create(self,data):
            # 获取老师的id
            tid = data.pop('id')
            # 获取学生的id
            student_id = data.pop('student_id')
            # 获取老师的实例
            teacherobj = models.Teacher.objects.filter(id=tid).first()
            # 添加数据
            teacherobj.students.set(
                student_id
            )
            # 返回老师的实例
            return teacherobj
    
        # 更新
        def update(self, instance, validated_data):
            # 获取学生的id列表
            student_id = validated_data.get('student_id')
            # 更新数据
            instance.students.set(student_id)
            # 返回实例
            return instance
    
  • 视图 views.py

    from rest_framework.views import APIView
    from rest_framework.response import Response
    from .seriliazers import *
    from . import models
    class TeacherView(APIView):
    
        # 添加关系
        def post(self,request):
            data = request.data
            obj = TeacherUnserializer(data=data)
            if obj.is_valid():
                obj.save()
                return Response({
                    "status":200
                })
            return Response({
                "status": 201
            })
        # 编辑关系
        def put(self,request):
            data = request.data
            tid = data.pop('id')
            print(tid)
            teacherobj = models.Teacher.objects.filter(id=tid).first()
            print(teacherobj)
            obj = TeacherUnserializer(instance=teacherobj,data=data)
            if obj.is_valid():
                obj.save()
                return Response({
                    'status':200,
                    'msg':'',
                })
            return Response({
                'status': 201,
                'msg': '',
            })
    
  • 提供的数据结构

    • 添加的数据结构

      {
          "id":2,
          "student_id":[1,2,3]
      }
      
    • 编辑的数据结构

      {
          "id":2,
          "student_id":[1,2,3]
      }
      

results matching ""

    No results matching ""