多对多序列化使用
创建一个经典的多对多关系:一个学生可以有多个老师,一个老师可以有个学生
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
中间表
- app04_student
创建序列化文件
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
from rest_framework.views import APIView from rest_framework.response import Response from .serializer import * from . import models # 学生类 class StudentView(APIView): # 查询所有的学生 def get(self,request): studentobj = models.Student.objects.all() stu = StudentSerializer(studentobj, many=True) return Response(stu.data)