Django如何在类而不是函数上使用``receiver''装饰器 [英] Django how to use the ``receiver`` decorator on a class instead on a function

查看:239
本文介绍了Django如何在类而不是函数上使用``receiver''装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Django信号接收器装饰器我有以下功能。

Using Django signals receiver decorator I have the following function.

@receiver(post_save)
def action_signal(sender, instance, created, **kwargs):
    pass

是否可以在类而不是函数上使用接收器装饰器?想要使用 __ init __ 方法等。

ie我该如何使类似的东西起作用...

i.e. How can I get something like this to work...

class ActionSignals

    def __init__(self):
        self.stuff

    @receiver(post_save)
    def action_signal(sender, instance, created, **kwargs):
        print(self.stuff)


推荐答案

使用接收器装饰器实际上没有任何意义。您何时期望实例化对象并运行 __ init __ 方法?

Using the receiver decorator on a class method doesn't really make sense. When do you expect the object to be instantiated and the __init__ method to run?

您可以对连接信号,而不是接收器装饰器。

You can use the manual method for connecting signals, instead of the receiver decorator.

第一个实例化对象:

action_signal = ActionSignals()

然后可以使用 connect 方法连接信号:

Then you can use the connect method to connect the signal:

post_save.connect(action_signal.action_signal)

这篇关于Django如何在类而不是函数上使用``receiver''装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆