• 多对多,本意就是多个一对多的关系

  • 定义多对多 ManyToManyField 字段

    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')
  • 多对多添加

    • 添加一条记录
    # 老师选择学生
    teacherobj = models.Teacher.objects.filter(id=1).first()
    studentobj = models.Student.objects.filter(id=1).first()
    teacherobj.students.add(studentobj)
    return Response('ok')
    # 学生选择老师
    studentobj = models.Student.objects.filter(id=1).first()
    teacherobj = models.Teacher.objects.filter(id=2).first()
    studentobj.stu.add(teacherobj)
    return Response('ok')
    • 添加多条记录
    # 老师选择多名学生
    teacherobj = models.Teacher.objects.filter(id=3).first()
    teacherobj.students.add(*[1,2,3,4])
    teacherobj.save()
    # 学生选择多名老师
    studentobj = models.Student.objects.filter(id=2).first()
    studentobj.stu.add(*[3,4])
    studentobj.save()
    • 添加不重复的记录
    # 老师选择多名学生
    teacherobj = models.Teacher.objects.filter(id=3).first()
    teacherobj.students.set(*[1,2,3,4])
    teacherobj.save()
    # 学生选择多名老师
    studentobj = models.Student.objects.filter(id=2).first()
    studentobj.stu.set(*[3,4])
    studentobj.save()
  • 多对多查询

    # 查询老师有多少名学生
    teacherobj = models.Teacher.objects.filter(id=3).first()
    stuobj = teacherobj.students.all()
    # 查询学生有多名老师
    studentobj = models.Student.objects.filter(id=2).first()
    teacherobj = studentobj.stu.all()
  • 多对多更新

    # 老师批量换学生
    teacherobj = models.Teacher.objects.filter(id=3).first()
    teacherobj.students.set([1,2,3,4])
    # 学生批量换老师
    studentobj = models.Student.objects.filter(id=3).first()
    studentobj.stu.set([1,2,3,4])
  • 多对多删除

    # 老师删除一个学生
    teacherobj = models.Teacher.objects.filter(id=3).first()
    studentobj = models.Student.objects.filter(id=2).first()
    teacherobj.students.remove(studentobj)
    # 学生删除一个老师
    studentobj = models.Student.objects.filter(id=3).first()
    teacherobj = models.Teacher.objects.filter(id=4).first()
    studentobj.stu.remove(teacherobj)
    studentobj.save()
    # 老师删除所有学生
    teacherobj = models.Teacher.objects.filter(id=1).first()
    teacherobj.students.clear()
    teacherobj.save()
    # 学生删除所有老师
    studentobj = models.Student.objects.filter(id=3).first()
    studentobj.stu.clear()
    studentobj.save()
05-23 18:49