Django Signal via Decorator on Model Method?

喜你入骨 提交于 2019-12-04 03:26:01

It's not clear from your example code, so I'd be asking if the signal listener actually has to be a @classmethod? I.e. Will a regular method do (and then use self.__class__ if you still need to access the class itself)? Does it need to be a method at all (can you just use a function)?

Another option might be to use a second method to listen to the signal and delegate the call to the @classmethod:

class ModelA(Model): 

    @classmethod 
    def do_observe_model_b_saved(cls, sender, instance, created, **kwargs): 
        # do some stuff 
        pass 

    @connect.post_save(ModelB) 
    def observe_model_b_saved(self, sender, instance, created, **kwargs): 
        self.do_observe_model_b_saved(sender, instance, created, **kwargs)

Could you make it a @staticmethod instead? That way, you can just swap the order of the decorators.

class ModelA(Model):

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

You'd have to refer to the class by full name instead of getting passed the cls argument, but this would allow you to keep a similar code organization.

Based off of Matt's answer, the @staticmethod trick worked for me. You can use a string to reference a model non-concretely.

class Foo(Model):

    @staticmethod
    @receiver(models.signals.post_save, sender='someappname.Foo')
    def post_save(sender, instance, created, **kwargs):
            print 'IN POST SAVE', sender, instance.id, created
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!