Django 1.2: How to connect pre_save signal to class method

旧时模样 提交于 2019-12-01 04:11:16

Rather than use a method on MyClass, you should just use a function. Something like:

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

pre_save.connect(before_save, sender=MyClass)

A working example with 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/

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). DataGreed addressed how to use it for a class method, and using signals with instance methods is pretty similar.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!