多对多接口
模型
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) stu = models.ManyToManyField(to='Student',related_name='teacher')
路由
urls.py
urlpatterns = [ path('student/',views.StudentView.as_view()), ]
序列化
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)
视图
view.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({ 'status':200, 'msg':'', 'data':stu.data })
返回数据结构
{ "status": 200, "msg": "", "data": [ { "id": 1, "name": "张三", "teacher": [ { "id": 1, "name": "张老师" } ] }, { "id": 2, "name": "李四", "teacher": [ { "id": 1, "name": "张老师" }, { "id": 2, "name": "李老师" } ] } ] }