多对多
用于表示多对多的关联关系。在数据库中通过第三张表来建立关联关系。
字段: ManyToManyField
字段参数to: 设置要关联的表
注意: 正向查询和反向查询同一对多规则。
例如:一个老师对应多个学生,一个学生对应多个老师。
(1)增
create():创建新的对象并且自动设置关系。
add():对象先存在,然后再设置关系。
1.create()
# 新学员 阿三 跟 波波老师学习
# teacher_obj = models.Teacher.objects.get(name=‘波波’)
# subject_obj = models.Subject.objects.get(name=‘python’)
#teacher_obj.student.create(name=‘阿三’, age=14, subject=subject_obj)
#subject属性设置对象
#teacher_obj.student.create(name=‘阿四’, age=14, subject_id=2)
#subject_id属性设置 id
2.add()
正向:
# teacher_obj = models.Teacher.objects.get(name=‘波波’)
# student_obj = models.Student()
# student_obj.name = ‘张三’
# student_obj.age = 22
# student_obj.subject_id = 2
# student_obj.save()
# teacher_obj.student.add(student_obj)
扩展:add() 方法可以添加多个关系–>>阿五和波波学了又和老王学
# teacher_obj = models.Teacher.objects.get(name=‘老王’)
# student_obj = models.Student.objects.get(name=‘阿五’)
#teacher_obj.student.add(student_obj)
#提示可以添加多个对象,或者添加多个对象id
# teacher_obj.student.add(student_obj,student_obj2,…)
# teacher_obj.student.add(1,2,3,4,…)
反向:
# teacher_obj = models.Teacher.objects.get(name=‘老王’)
# student_obj = models.Student()
# student_obj.name = ‘李四’
# student_obj.age = 11
# student_obj.subject_id = 2
# student_obj.save()
# student_obj.teacher_set.add(teacher_obj)
(2)删
remove():解除某个对象之间的关系
clear() :清除某个对象关联的所有关系
delete():删除某个对象及其对应的关系
1.remove(): 解除关系
正向操作:
练习1:阿五不和 老王学
teacher_obj = models.Teacher.objects.get(name=‘老王’)
student_obj = models.Student.objects.get(name=‘阿五’)
teacher_obj.student.remove(student_obj) # 也可以根据id 删除
反向操作:
teacher_obj = models.Teacher.objects.get(name=‘波波’)
student_obj = models.Student.objects.get(name=‘张三’)
student_obj.teacher_set.remove(teacher_obj)
2.clear()
正向操作:
老王高升了
teacher_obj = models.Teacher.objects.get(name=‘老王’)
teacher_obj.student.clear()
反向操作:
张三休学了
student_obj = models.Student.objects.get(name=‘张三’)
student_obj.teacher_set.clear()
3.delete()
王五退学
models.Student.objects.get(name=‘张三’).delete()
老王离职了
models.Teacher.objects.get(name=‘老王’).delete()
(3)改
set(): 将某个对象的关系修改为 指定的关系(以前的关系会被删除)
正向操作:
老王 现在只教id 为 15,16 的对象
teacher_obj = models.Teacher.objects.get(name=‘老王’)
teacher_obj.student.set([15, 16])
提示:也可以是对象
teacher_obj.student.set([obj1,obj2,obj3…])
反向操作:
王五想和波波和老王学习
student_obj = models.Student.objects.get(name=‘王五’)
student_obj.teacher_set.set([2, 3])
(4)查
正向: 波波老师 教过的学生
# teacher_obj = models.Teacher.objects.get(name=‘波波’)
# student_obj_list = teacher_obj.student.all()
# <QuerySet [<Student: name:张三>, <Student: name:李四>]>
# print(student_obj_list)
反向: 查询 张三 被哪些老师教过
# student_obj = models.Student.objects.get(name=‘张三’)
# teacher_obj_list = student_obj.teacher_set.all()
# print(teacher_obj_list)
# <QuerySet [<Teacher: name:波波>]>