django 多对多操作 模型 from django.db import models# 老师class Teacher(models.Model): name = models.CharField(max_length=32)# 学生class Student(models.Model): name = models.CharField(max_length=32) teachers = models.ManyToManyFie
django 多对多操作
模型
from django.db import models # 老师 class Teacher(models.Model): name = models.CharField(max_length=32) # 学生 class Student(models.Model): name = models.CharField(max_length=32) teachers = models.ManyToManyField(to='Teacher',on_delete=models.CASCADE)
查询
# 通过老师查学生 teacher = Teacher.objects.filter(id=1).first() students = teacher.student_set.all() # 获取所有学生信息 # 通过学生查老师 student = Student.objects.filter(id=2).first() teachers = student.teachers.all() # 获取所有老师的信息
添加
# 学生选择老师 t1 = Teacher.objects.filter(id=1).first() t2 = Teacher.objects.filter(id=2).first() t3 = Teacher.objects.filter(id=3).first() s1 = Student.objects.filter(id=4).first() s1.teacher.add(*[t1,t2,t3]) # 学生选择了三个老师 # 老师选择学生 s1 = Student.objects.filter(id=4).first() s2 = Student.objects.filter(id=5).first() t1.student_set.add(*[s1,s2]) # 老师选择了两个学生
清空
# 通过老师清空 t1 = Teacher.objects.filter(id=1).first() t1.student.clear() # 通过学生清空 s1 = Student.objects.filter(id=1).first() s1.teacher.clear()
删除指定数据
t1 = Teacher.objects.filter(id=1).first() s1 = Student.objects.filter(id=1).first() # 以老师的角度删除与学生之间的关系 t1.student_set.remove(s1) # 以学生的角度删除与老师之间的关系 s1.teacher.remove(t1)