【发布时间】:2019-10-19 12:38:57
【问题描述】:
问题标题就是一句话,但希望下面的代码能把它弄清楚:
class Foo(models.Model):
...
class AbstractParent(models.Model):
foos = models.ManyToManyField(
Foo,
related_name='%(app_label)s_%(class)s_related'
)
def bar(self):
...
class Meta:
abstract = True
class ChildOne(AbstractParent):
...
class ChildTwo(AbstractParent):
...
假设我的应用的标签是“myapp”。
基本上,ChildOne 和ChildTwo 的基类与Foo 类具有M2M。我想做的是:每当保存Foo 类的对象时,我想调用ClassOne 和ClassTwo 的所有对象的bar() 方法,这与Foo 有关系对象通过foos 字段。为此,我尝试编写一个简单的信号:
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=Foo)
def call_bar_for_all_related_objects_to_foo(sender, instance, **kwargs):
# Do the thing
在这一点上,我有点迷失了。如何查询AbstractParent 类的所有子类并在信号中与instance 相关时调用它们的bar() 方法?理想情况下,我只想查询我的数据库一次,并且在一次查询中,我想获取与信号中的instance 相关的ChildOne 和ChildTwo 的所有对象。请注意,在我的实际模型中,AbstractParent 有两个以上的子类,因此请记住这一点的答案。感谢您的帮助。
【问题讨论】:
标签: django django-models many-to-many django-signals