anirvan
anirvan

Reputation: 4877

Django clear ManyToManyField associations on update

On update, I'm trying to clear all associations from a model having ManyToMany association with another. However, the associations are still persisted.

To explain my point, consider the following 2 models:

class Teacher(models.Model):
    school = models.ForeignKey(School)
    students = models.ManyToManyField(Student)

class Student(models.Model):
    school = models.ForeignKey(School)

Now, I wish to remove all associations of teacher to student, or vice-versa, whenever the shool changes for either model. So I decided to override the save() method for Teacher first.

class Teacher(models.Model):
     ...
     ...
     def save(self, *args, **kwargs):
          # after figuring out "school_id" changed
          self.students.remove()

          super(Teacher, self).save(*args, **kwargs)

However, once the Teacher object is persisted, I can see that all the Student associations are reinserted into the association table.

Am I missing out something here, or, is there some way to instruct the models.Model.save() not to reinsert the associations?

Thanks!

Upvotes: 0

Views: 295

Answers (1)

levi
levi

Reputation: 22697

You need to use clear() method not remove(). According to docs, delete() removes a specified model objects from the related object set

>>> b = Blog.objects.get(id=1)
>>> e = Entry.objects.get(id=234)
>>> b.entry_set.remove(e) # Disassociates Entry e from Blog b.

But, that is not your case, you want to disassociate all of them not a specified one.

 def save(self, *args, **kwargs):
      # after figuring out "school_id" changed
      self.students.clear()

      super(Teacher, self).save(*args, **kwargs)

Upvotes: 1

Related Questions