所以我读了Django源代码(后1.5),你现在可以将多个多个信号注册到接收函数:
def receiver(signal, **kwargs):
"""
A decorator for connecting receivers to signals. Used by passing in the
signal (or list of signals) and keyword arguments to connect::
@receiver(post_save, sender=MyModel)
def signal_receiver(sender, **kwargs):
...
@receiver([post_save, post_delete], sender=MyModel)
def signals_receiver(sender, **kwargs):
...
"""
... implementation code...
但是,我想将来自不同发件人的多个post_save信号注册到同一个函数。现在,我只是打电话给
post_save.connect(fn_name, model_name)
我拥有的每个型号。使用新的Django 1.5 @receiver装饰器功能有更好的方法吗?
答案 0 :(得分:124)
你可以使用@receiver decorator:
@receiver(post_save, sender=Model1)
@receiver(post_save, sender=Model2)
@receiver(post_save, sender=Model3)
def my_signal_handle(sender , **kwargs)
# some code here
答案 1 :(得分:28)
根据Django documentation on receivers,接收器默认情况下不需要连接到特定的发件人。所以你所描述的是默认的Django功能。
换句话说,要使用@receiver
装饰器执行此操作,您只需在装饰器中不指定发件人。例如:
@receiver(post_save) # instead of @receiver(post_save, sender=Rebel)
def set_winner(sender, instance=None, created=False, **kwargs):
list_of_models = ('Rebel', 'Stormtrooper', 'Battleground')
if sender.__name__ in list_of_models: # this is the dynamic part you want
if created: # only run when object is first created
... set the winner ...
这假定模型看起来像:
class Rebel(models.Model):
...
class Stormtrooper(models.Model):
...
class Battleground(models.Model):
...
答案 2 :(得分:19)
您可以跳过model_name
,然后您将连接到所有型号的post_save。然后,您可以过滤处理程序中的正确模型:
post_save.connect(foo)
def foo(sender, **kwargs):
if sender not in [FooModel, BarModel]:
return
... actual code ...
或者您可以根据模型中的字段进行过滤:
def foo(sender, **kwargs):
if not getattr(sender, 'process_by_foo', False):
return
... actual code ...
答案 3 :(得分:1)
def receiver_with_multiple_senders(signal, senders, **kwargs):
"""
Based on django.dispatch.dispatcher.receiver
Allows multiple senders so we can avoid using a stack of
regular receiver decorators with one sender each.
"""
def decorator(receiver_func):
for sender in senders:
if isinstance(signal, (list, tuple)):
for s in signal:
s.connect(receiver_func, sender=sender, **kwargs)
else:
signal.connect(receiver_func, sender=sender, **kwargs)
return receiver_func
return decorator