简体   繁体   English

Django 1.2:如何将pre_save信号连接到类方法

[英]Django 1.2: How to connect pre_save signal to class method

I am trying to define a "before_save" method in certain classes in my django 1.2 project. 我试图在我的django 1.2项目中的某些类中定义“before_save”方法。 I'm having trouble connecting the signal to the class method in models.py. 我在将信号连接到models.py中的类方法时遇到问题。

class MyClass(models.Model):
    ....
    def before_save(self, sender, instance, *args, **kwargs):
        self.test_field = "It worked"

I've tried putting pre_save.connect(before_save, sender='self') in 'MyClass' itself, but nothing happens. 我已经尝试将pre_save.connect(before_save,sender ='self')放在'MyClass'本身,但没有任何反应。

I've also tried putting it at the bottom of the models.py file: 我也尝试将它放在models.py文件的底部:

pre_save.connect(MyClass.before_save, sender=MyClass)

I read about connecting signals to class methods here , but can't figure out the code. 在这里读到了将信号连接到类方法,但无法弄清楚代码。

Anybody know what I'm doing wrong? 谁知道我做错了什么?

A working example with classmethod : 使用classmethod的一个工作示例:

class MyClass(models.Model):
    #....
    @classmethod
    def before_save(cls, sender, instance, *args, **kwargs):
        instance.test_field = "It worked"

pre_save.connect(MyClass.before_save, sender=MyClass)

There's also a great decorator to handle signal connections automatically: http://djangosnippets.org/snippets/2124/ 还有一个很棒的装饰器可以自动处理信号连接: http//djangosnippets.org/snippets/2124/

I know this question is old, but I was looking for an answer to this earlier today so why not. 我知道这个问题已经过时了,但我今天早些时候正在寻找答案,所以为什么不呢。 It seems from your code that you actually wanted to use an instance method (from the self and the field assignment). 从您的代码中可以看出,您实际上想要使用实例方法(来自self和字段赋值)。 DataGreed addressed how to use it for a class method, and using signals with instance methods is pretty similar. DataGreed解决了如何将它用于类方法,并且使用带有实例方法的信号非常相似。

class MyClass(models.Model)

    test_field = models.Charfield(max_length=100)

    def __init__(self, *args, **kwargs):
        super(MyClass, self).__init__(*args, **kwargs)
        pre_save.connect(self.before_save, sender=MyClass)

    def before_save(self, sender, instance, *args, **kwargs):
        self.test_field = "It worked"

I'm not sure if this is a good idea or not, but it was helpful when I needed an instance method called on an object of class A before save from class B. 我不确定这是不是一个好主意,但是当我从B类保存之前需要一个在A类对象上调用的实例方法时,它很有用。

Rather than use a method on MyClass, you should just use a function. 您应该只使用一个函数,而不是在MyClass上使用方法。 Something like: 就像是:

def before_save(sender, instance, *args, **kwargs):
    instance.test_field = "It worked"

pre_save.connect(before_save, sender=MyClass)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM