Search code examples
pythondjangomany-to-manydjango-3.0

Django: update field of ManyToMany instance when it's set


Is it possible to do something when setting ManyToMany relations with .set()?

Let's say, we have:

class ModelA():
  b_models = models.ManyToManyField(ModelB, related_name="as", through="ModelMN")

class ModelMN():
  model_a = models.ForeignKey(ModelA)
  model_b = models.ForeignKey(ModelB)

And when we have an instance of Model A and list of Model B instances:

a = ModelA()
a.set([b1, b2, b3])

When calling .set(), an instace of ModelMN is created for every a-b relationship. Is it possible to modify a field of that instance (every ModelMN instance), everytime it is created?

Overriding .save() method on ModelMN seems not to be working.


Solution

  • I was looking for m2m_changed signal.

    @receiver(m2m_changed, sender=ModelA.b_models.through)
    function do_something(sender, **kwargs):
        ...