首页 > 解决方案 > 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.

标签: pythondjangomany-to-manydjango-3.0

解决方案


我在寻找m2m_changed信号。

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

推荐阅读