70

因此,我阅读了 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 装饰器功能是否有更好的方法来做到这一点?

4

4 回答 4

203

您可以使用@receiver装饰器做到这一点:

from django.dispatch import receiver

@receiver(post_save, sender=Model1)
@receiver(post_save, sender=Model2)
@receiver(post_save, sender=Model3)
def my_signal_handle(sender , **kwargs)
    # some code here
于 2015-08-26T15:37:26.087 回答
38

根据关于接收者的 Django 文档默认情况下接收者不需要连接到特定的发送者。所以你所描述的是默认的 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):
    ...
于 2013-09-12T07:00:44.173 回答
22

您可以跳过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 ...
于 2013-07-07T12:31:25.563 回答
5
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
于 2018-07-22T02:28:20.373 回答