zoukankan      html  css  js  c++  java
  • DRF 多对多序列化和反序列化

    Django 序列化和反序列化

    一、 序列化

    • 查询所有的学生的信息,包括任课老师

      • models.py

        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)
            students = models.ManyToManyField(to='Student',related_name='teacher')
        
      • serializer.py

        from rest_framework import serializers
        from . import models
        
        # 老师序列化
        class TeacherSerializer(serializers.ModelSerializer):
            class Meta:
                model = models.Teacher
                fields = ('id','name')
        # 学生序列化
        class StudentSerializer(serializers.Serializer):
                name = serializers.CharField(max_length=32)
                teacher = TeacherSerializer(many=True,read_only=True)
        
      • views.py

        # 查询所有的学生对应的老师
        studentobj = models.Student.objects.all()
        stu = StudentSerializer(studentobj,many=True)
        return Response(stu.data)
        
      • 结果

        [
            {
                "name": "小张",
                "teacher": [
                    {
                    "id": 3,
                    "name": "郑老师"
                    }
                ]
            },
            {
                "name": "小李",
                "teacher": [
                {
                    "id": 4,
                    "name": "董老师"
                    }
                ]
            },
            {
            "name": "小夏",
            "teacher": []
            },
            {
            "name": "小徐",
            "teacher": []
            }
        ]
        
    • 查询所有的老师的信息,包括所教学生

      • models.py

        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)
        students = models.ManyToManyField(to='Student',related_name='teacher')
        
      • serializer.py

        from rest_framework import serializers
        from . import models
        
        # 学生序列化
        class StudentSerializer(serializers.ModelSerializer):
            class Meta:
                model = models.Teacher
                fields = ('id','name')
        # 老师序列化
        class TeacherSerializer(serializers.Serializer):
            name = serializers.CharField(max_length=32)
            students = StudentSerializer(many=True,read_only=True)
        
      • views.py

        teacherobj = models.Teacher.objects.all()
        teach = TeacherSerializer1(teacherobj,many=True)
        return Response(teach.data)
        
      • 结果

        [
            {
                "name": "王老师",
                "students": []
                },
                {
                "name": "刘老师",
                "students": []
                },
            {
                "name": "郑老师",
                "students": [
                    {
                        "id": 1,
                        "name": "小张"
                    }
                ]
            },
            {
                "name": "董老师",
                "students": [
                    {
                    "id": 2,
                    "name": "小李"
                    }
                ]
            }
        ]
        

    二、反序列化

    • 老师添加学生

      • models.py

        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)
            students = models.ManyToManyField(to='Student',related_name='teacher')
        
      • serializer.py

        # 反序列化
        class TeacherUnserializer(serializers.Serializer):
            id = serializers.IntegerField()
            student_id = serializers.ListField()
        
            def create(self,data):
                tid = data.pop('id')
                student_id = data.pop('student_id')
                teacherobj = models.Teacher.objects.filter(id=tid).first()
                teacherobj.students.set(
                    student_id
                )
                return teacherobj
        
      • views.py

        data = {
            "id":2,
            "student_id":[1,2,3,4]
        }
        obj = TeacherUnserializer(data=data)
        if obj.is_valid():
            obj.save()
        print(obj.errors)
        return Response('ok')
        
    • 学生添加老师

      • models.py

        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)
            students = models.ManyToManyField(to='Student',related_name='teacher')
        
      • serializer.py

        # 反序列化
        class StudentUnserializer(serializers.Serializer):
            id = serializers.IntegerField()
            teacher_id = serializers.ListField()
        
            def create(self,data):
                id = data.pop('id')
                teacher_id = data.pop('teacher_id')
                studentobj = models.Student.objects.filter(id=id).first()
                studentobj.teacher.set(
                    teacher_id
                )
                return studentobj
        
      • views.py

        data = {
            "id": 2,
            "teacher_id": [1, 2, 3, 4]
        }
        obj = StudentUnserializer(data=data)
        if obj.is_valid():
            obj.save()
        print(obj.errors)
        return Response('ok')
        

    非常感谢刘同学对我代码的指正,非常的感谢!

  • 相关阅读:
    CSS清除浮动常用方法小结
    json格式的javascript对象用法分析
    jQuery on()方法绑定动态元素的点击事件无响应的解决办法
    一道思考题(二进制枚举的应用的想法)切金条
    对于excel中,无法把字符型转成数字型解决办法
    对于excel中,无法把字符型转成数字型解决办法
    python文本挖掘输出权重,词频等信息,画出3d权重图
    python文本挖掘输出权重,词频等信息,画出3d权重图
    python使用scikit-learn计算TF-IDF
    python使用scikit-learn计算TF-IDF
  • 原文地址:https://www.cnblogs.com/wuxiaoshi/p/11831466.html
Copyright © 2011-2022 走看看