工作,我有兩個表: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)
,我需要自動填入驗證表中增加新的廣告之後。
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()?」
哪一部分不工作? – 2011-03-29 13:09:10
代碼似乎是正確的,什麼不工作?驗證記錄沒有被創建? – 2011-03-29 13:15:59
在下面回答。 – mktums 2011-03-29 13:31:43