1.models.py from django.db import models #自动生成的关联表的优点是要写的代码比较少,缺点是关联表只能有三列,适用于简单的情况, #而自定义的关联表可以写很多列,适用于复杂的情况。 class Teachers(models.Model): name = models.CharField(max_length=32) #m是连接Classes的通道,在数据库自动创建表app01_teachers_m, #字段名是id、teachers_id、classes_id m = models.ManyToManyField('Classes') class Classes(models.Model): title = models.CharField(max_length=32)
2. views.py from django.shortcuts import render,HttpResponse from app01 import models def test(request): # models.Teachers.objects.create(name='小明') # models.Teachers.objects.create(name='小红') # models.Teachers.objects.create(name='小方') # # models.Classes.objects.create(title='全栈1期') # models.Classes.objects.create(title='全栈2期') # models.Classes.objects.create(title='全栈3期') # models.Classes.objects.create(title='全栈4期') row = models.Teachers.objects.filter(name='小明').first() #增 # app01_teachers_m表的classes_id增加1,2,3,4 row.m.add(1,2) row.m.add(*[3,4]) # 删 # app01_teachers_m表的classes_id删除3,4 row.m.remove(3,4) # row.m.remove(*[3,4]) #删除全部 row.m.clear() #改 #app01_teachers_m表的classes_id重设为2,3 row.m.set([2,3]) #查 #找到Classes表中小明老师任教的所有班级 classes_list = row.m.all() for row in classes_list: print(row.title) # 找到Classes表中小明老师任教的全栈2期的行 # row = row.m.filter(title='全栈2期') #反向操作 #找到任教全栈2期的老师都有谁 row = models.Classes.objects.filter(title='全栈2期').first() teachers_list = row.teachers_set.all() for row in teachers_list: print(row.name) return HttpResponse('...')