后端接口
模型
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')
路由
urls.py
urlpatterns = [ path('teacher/',views.TeacherView.as_view()), ]
反序列化
serializer.py
from rest_framework import serializers from . import models # 反序列化 class TeacherUnserializer(serializers.Serializer): 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] }