21

也许只是太晚了,但我无法弄清楚为什么这不起作用。当我有一个 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)

有没有善良的灵魂可以阻止我把头撞到墙上?谢谢。

4

1 回答 1

32

在我看来,第二个问题是您使用的是无界方法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)

参考:

  1. 从 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.
    
  2. Difference between @classmethod and @staticmethod: What is the difference between @staticmethod and @classmethod in Python?

于 2012-09-23T08:35:17.590 回答