使用Django的post_save()信号

时间:2011-03-29 12:53:54

标签: python django-signals

我有两张桌子:

class Advertisement(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    author_email = models.EmailField()

class Verification(models.Model):
    advertisement = models.ForeignKeyField(Advertisement)
    key = models.CharField(max_length=32)

我需要在添加新广告后自动填充Verification表。

def gen_key(sender, instance, created, **kwargs):
    if created:
        from hashlib import md5
        vkey = md5("%s%s" % (instance.author_email, instance.created_at))
        ver = Verification(advertisement=instance)
        ver.key = vkey
        ver.save()

post_save.connect(gen_key, sender=Advertisement)

当然它不起作用。 Django 1.2 问:我该怎么做?


好的,半解决了。
问题是父模型的post_save()不会调用子模型 所以你可以通过直接提供子课来解决它。

class Advertisement(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    author_email = models.EmailField()

class Sale(Advertisement):
    rooms = models.IntegerField(max_length=1)
    subway = models.ForeignKey(Subway)

class Verification(models.Model):
    advertisement = models.ForeignKeyField(Advertisement)
    key = models.CharField(max_length=32)

def gen_key(sender, instance, created, **kwargs):
    code goes here
post_save.connect(gen_key, sender=Sale, dispatch_uid="my_unique_identifier")

接下来的问题是“如何使用post_save()的父类?”

1 个答案:

答案 0 :(得分:4)

而不是连接到特定的发件人,只需连接到post_save,然后检查处理程序中保存的实例的类,例如

def gen_key(sender, **kwargs):
    if issubclass(sender, Advertisement):
        code goes here
post_save.connect(gen_key, dispatch_uid="my_unique_identifier")