mangtomant 增删改查

Django下ManytoMany 增删改查

建立学生类老师类多对多关系,用ManytoManyField,迁移同步后自动生成中间表tb_Teacher_Student


# 学生类

class Student(models.Model):

  name = models.CharField(max_length=32)

   class Meta:

     db_table = 'tb_Student'

# 老师类

class Teacher(models.Model):

   name = models.CharField(max_length=32)

   students = models.ManyToManyField('Student',related_name='teacher')

   class Meta:

     db_table = 'tb_Teacher'

 

增,改add()

t1=Teacher(name='jotaro') # 实例化老师

s1=Student(name='dio') # 实例化学生

t1.students.add(s1)

t1.save()

s1.save()

print(t1.name)

 

# 批量建立对象多对多的关系,存在则覆盖 set()

t1=Teacher(name='jotaro')

s1=Student(name='dio')

s2=Student(name='kira')

s3=Student(name='paul')

s1.save()

s2.save()

s3.save()

t1.save()

t1.students.add(s1)

print(t1.students.all())

t1.students.set([s2,s3])

print(t1.students.all())

 

 

1.delete(),当删除其中一方的对象,多对多表里对应的关系行也自动删除

teacher = Teacher.objects.get(students__name='kirakira')

print(teacher.students.all())

stu = Student.objects.get(name='kirakira')

stu.delete()

print(teacher.students.all())

 

如果单纯想去除单个学生和老师的多对多关系,而不想删除任何一方的数据,可以用remove()

t1=Teacher(name='jotaro')

s1=Student(name='dio')

s1.save()

t1.save()

t1.students.add(s1)

print(t1.students.all())

 t1.students.remove(s1)

print(s1)

print(t1.students.all())

posted on 2021-02-19 16:15  Plyc  阅读(79)  评论(0编辑  收藏  举报

导航