多对多删除
模型
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='stu')
视图
老师删除一个学生
from rest_framework.views import APIView from rest_framework.response import Response from . import models # 老师类 class TeacherView(APIView): def delete(self, request): teacherobj = models.Teacher.objects.filter(id=3).first() stuobj = models.Student.objects.filter(id=2).first() teacherobj.students.remove(stuobj) return Response({ "status": 200, "msg":"删除成功" })
老师删除所有学生
from rest_framework.views import APIView from rest_framework.response import Response from . import models # 老师类 class TeacherView(APIView): def delete(self, request): teacherobj = models.Teacher.objects.filter(id=3).first() teacherobj.students.clear() return Response({ "status": 200, "msg":"删除成功" })
学生删除一个老师
from rest_framework.views import APIView from rest_framework.response import Response from . import models # 学生类 class StudentView(APIView): def delete(self, request): stuobj = models.Student.objects.filter(id=2).first() teacherobj = models.Teacher.objects.filter(id=3).first() stuobj.stu.remove(teacherobj) return Response({ "status": 200, "msg":"删除成功" })
学生删除所有老师
from rest_framework.views import APIView from rest_framework.response import Response from . import models # 学生类 class StudentView(APIView): def delete(self, request): stuobj = models.Student.objects.filter(id=2).first() stuobj.stu.clear() return Response({ "status": 200, "msg":"删除成功" })