我有信号接收器的单独python模块,它被称为$ docker run -v /path/to/executable:/my_exe debian /my_exe
,并在signals.py
的{{1}}方法中导入。
在本单元中,我为特定模型实现了ready()
和AppConfig
信号接收器,并通过装饰器进行了注册:
post_save
它工作正常。
但是,当我以相同的方式添加到post_delete
相同信号的接收器时,但来自不同的特定模型:
@receiver(post_save, sender=MyModel)
def generate_smth(sender, instance, created, **kwargs):
...
我的功能停止接收信号。但是如果我将接收器移动到单独的python模块signals.py
和@receiver(post_save, sender=AnotherModel)
def generate_smth(sender, instance, created, **kwargs):
...
并导入mymodel_signals.py
中的两个模块,那么所有模块都会再次工作。
为什么不能将接收器保留在一个模块中?
答案 0 :(得分:1)
@receiver(post_save, sender=MyModel)
@receiver(post_save, sender=AnotherModel)
def generate_smth(sender, instance, created, **kwargs):
if sender.__name__ = 'MyModel':
# Bar
else:
# Foo
答案 1 :(得分:0)
您希望两个函数具有相同的行为吗?如果是,您可以这样做:
def do_smth(sender, instance, created, **kwargs):
...
@receiver(post_save, sender=MyModel)
def generate_smth(sender, instance, created, **kwargs):
do_smth(sender, instance, created, **kwargs)
@receiver(post_save, sender=AnotherModel)
def generate_another_smth(sender, instance, created, **kwargs):
do_smth(sender, instance, created, **kwargs)