编程语言
首页 > 编程语言> > python – 使用Django的post_save()信号

python – 使用Django的post_save()信号

作者:互联网

我有两张桌子:

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()的父类?”

解决方法:

而不是连接到特定的发送者,只需连接到post_save,并检查处理程序中保存的实例的类,例如

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

标签:python,django-signals
来源: https://codeday.me/bug/20190626/1296669.html