gpt4 book ai didi

django - 用一个接收器合并多个 post_save 信号

转载 作者:行者123 更新时间:2023-11-28 19:35:00 27 4
gpt4 key购买 nike

所以我阅读了 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 装饰器功能来做到这一点?

最佳答案

您可以使用 @receiver decorator 来做到这一点:

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

关于django - 用一个接收器合并多个 post_save 信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17507784/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com