python - 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.
解决方案
我在寻找m2m_changed
信号。
@receiver(m2m_changed, sender=ModelA.b_models.through)
function do_something(sender, **kwargs):
...
推荐阅读
- java - Java,如何从 x,y 坐标列表中制作 PNG
- laravel - 从另一个用户路由 laravel 5.6 阻止用户
- sql - 如何获得总重复行数?
- java - MVC 模式不特定于 JDBC,关于三层架构
- ansible - 获取 Ansible 本地主机 Ipv4.address
- php - 查找数组中的第一个重复项
- python - List vs Dict 并使用 Zip:list(zip) 工作正常,但 dict(zip) 有点偏离
- java - 从数据库列填充列表视图而不重复值
- java - Python 与 Java,For 循环
- html - 如何让我插入的视频显示在我的页面上?