我怎样才能有一个Django信号调用模型方法?

也许这只是晚了,但我不明白为什么这不起作用。 当我有一个post_save信号调用一个通用函数时,它可以工作,但是当我有一个post_save信号从模型中调用一个方法时,什么都不会发生。 这是可以工作的代码:

class Revision(models.Model):
    # Model junk...

def send_email(sender, instance, created, **kwargs):
    if created:
        print "DO STUFF"

signals.post_save.connect(send_email, sender=Revision)

但是这不起作用:

class Revision(models.Model):
    # Model junk...

    def send_email(sender, instance, created, **kwargs):
        if created:
            print "DO STUFF"

signals.post_save.connect(Revision.send_email, sender=Revision)

那里有一个善良的灵魂,能让我不用把头撞到墙上? 谢谢。


在我看来,第二个问题是你正在使用无限制的send_mail方法。 如果你真的想从一个类中调用send_mail@classmethod@staticmethod可以帮助你:

class Revision(models.Model):
    # Model junk...

    @classmethod
    def send_email(cls, sender, instance, created, **kwargs):
        if created:
            print "DO STUFF"

signals.post_save.connect(Revision.send_email, sender=Revision)

要么

class Revision(models.Model):
    # Model junk...

    @staticmethod
    def send_email(sender, instance, created, **kwargs):
        if created:
            print "DO STUFF"

signals.post_save.connect(Revision.send_email, sender=Revision)

另外,如果不使用这些装饰器,则可以传递有界的实例方法:

class Revision(models.Model):
# Model junk...

    def send_email(self, sender, instance, created, **kwargs):
        if created:
            print "DO STUFF"

signals.post_save.connect(Revision().send_email, sender=Revision)

参考文献:

  • 从Django源代码:

    def connect(self, receiver, sender=None, weak=True, dispatch_uid=None):
        """
        Connect receiver to sender for signal.
    
        Arguments:
    
            receiver
                A function or an instance method which is to receive signals.
                Receivers must be hashable objects.
    
                If weak is True, then receiver must be weak-referencable (more
                precisely saferef.safeRef() must be able to create a reference
                to the receiver).
    
                Receivers must be able to accept keyword arguments.
    
                If receivers have a dispatch_uid attribute, the receiver will
                not be added if another receiver already exists with that
                dispatch_uid.
    
  • @classmethod@staticmethod之间的@classmethod :Python中的@classmethod@staticmethod什么区别?

  • 链接地址: http://www.djcxy.com/p/9183.html

    上一篇: How can I have a Django signal call a model method?

    下一篇: How can static method access class variable in Python?