python - Django 在模型方法上通过装饰器发送信号?

标签 python django django-models decorator django-signals

我正在尝试做类似 these proposed signal decorators 的事情.除了具有将装饰方法连接到信号的装饰器(将信号的发送者作为装饰器的参数)之外,我还想在类方法上使用装饰器。

我想像这样使用装饰器:

class ModelA(Model):

    @connect.post_save(ModelB)
    @classmethod
    def observe_model_b_saved(cls, sender, instance, created, **kwargs):
        # do some stuff
        pass

装饰器是:

from django.db.models import signals
def post_save(sender):
    def decorator(view):
        signals.post_save.connect(sender=sender, receiver=view)
        return view
    return decorator

执行此操作时出现的错误是:

File "/Library/Python/2.6/site-packages//lib/python2.6/site-packages/django/dispatch/dispatcher.py", line 78, in connect
AssertionError: Signal receivers must be callable.

我想问题是 @classmethod 返回了一个不可调用的类方法对象。我真的不明白 classmethod 是如何工作的,但我从 this reference page 推测类方法对象在从类中访问之前不会被转换为可调用对象,例如 ModelA.observe_model_b_saved。有什么方法可以 (1) 将我的方法定义为模型上的类或实例方法,以及 (2) 直接在方法定义上使用装饰器将其连接到信号?谢谢!

最佳答案

你能把它改成@staticmethod 吗?这样,您只需交换装饰器的顺序即可。

class ModelA(Model):

    @staticmethod
    @connect.post_save(ModelB)
    def observe_model_b_saved(sender, instance, created, **kwargs):
        # do some stuff
        pass

您必须通过全名而不是传递 cls 参数来引用该类,但这将允许您保持类似的代码组织。

关于python - Django 在模型方法上通过装饰器发送信号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2310676/

相关文章:

python - 在 Python 中显示数字 int

python - Scikit 的管道 - 如何访问特定阶段的结果

python - Django 从注释计数中排除

python - 使用 DRF 反向过滤 Django 模型

python - 以更简单的方式调用不同的函数

python - 如何序列化字符串列表

python - Django:AutoSlug 错误 "slug is defined before trying to ensure uniqueness"

django - 如何防止此 PostgreSQL 查询中的全表扫描?

python - InvalidBasesError : Cannot resolve bases for [<ModelState: 'users.GroupProxy' >]

python - 无法从 Windows 上的 Python 连接到 MSSQL Server