DRF 多對多序列化和反序列化

Django 序列化和反序列化

1、 序列化python

  • 查詢全部的學生的信息,包括任課老師django

    • models.pyrest

      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.pycode

      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.pyclass

      # 查詢全部的學生對應的老師
      studentobj = models.Student.objects.all()
      stu = StudentSerializer(studentobj,many=True)
      return Response(stu.data)
    • 結果import

      [
          {
              "name": "小張",
              "teacher": [
                  {
                  "id": 3,
                  "name": "鄭老師"
                  }
              ]
          },
          {
              "name": "小李",
              "teacher": [
              {
                  "id": 4,
                  "name": "董老師"
                  }
              ]
          },
          {
          "name": "小夏",
          "teacher": []
          },
          {
          "name": "小徐",
          "teacher": []
          }
      ]
  • 查詢全部的老師的信息,包括所教學生object

    • models.pyList

      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.pymodel

      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 = TeacherSerializer(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": "小李"
                  }
              ]
          }
      ]

2、反序列化

  • 老師添加學生

    • 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')
相關文章
相關標籤/搜索