Django 1.2: How to connect pre_save signal to class method

前端 未结 3 568
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 11:34

I am trying to define a \"before_save\" method in certain classes in my django 1.2 project. I\'m having trouble connecting the signal to the class method in models.py.

3条回答
  •  隐瞒了意图╮
    2021-01-12 12:23

    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.

提交回复
热议问题