多对多添加
模型
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 post(self, request): teacherobj = models.Teacher.objects.filter(id=1).first() studentobj = models.Student.objects.filter(id=2).first() teacherobj.students.add(studentobj) return Response({ "status": 200 })
学生选择老师
from rest_framework.views import APIView from rest_framework.response import Response from . import models # 学生类 class StudentView(APIView): def post(self,request): studentobj = models.Student.objects.filter(id=1).first() teacherobj = models.Teacher.objects.filter(id=1).first() studentobj.stu.add(teacherobj) return Response({ "status":200 })
老师选择多名学生
from rest_framework.views import APIView from rest_framework.response import Response from . import models # 老师类 class TeacherView(APIView): def post(self, request): teacherobj = models.Teacher.objects.filter(id=1).first() teacherobj.students.set(*[1,2,3,4]) return Response({ "status": 200 })
学生选择多名老师
from rest_framework.views import APIView from rest_framework.response import Response from . import models # 学生类 class StudentView(APIView): def post(self,request): studentobj = models.Student.objects.filter(id=1).first() studentobj.stu.set(*[1,2,3,4]) return Response({ "status":200 })