这是我的代码:
class Invitation(models.Model):
#other fields here
Code = models.CharField(max_length=128, null=True, blank=True)
Tags = models.ManyToManyField("CategorieInvitation", null=True, blank=True)
Tags = models.ManyToManyField("Usage", null=True, blank=True)
Note = models.CharField(max_length=128, null=True, blank=True)
Used = models.BooleanField(default=False, blank=True)
SendTo = models.EmailField(null=True, blank=True)
# a revoir
def post_save(self, model_instance, add):
if self.Code.__len__() == 0 :
self.Code = generate_invitation(1)[0]
self.save()
如果代码为空或如果在django-admin界面中创建,则如何将代码替换为generate_invitation的结果?
问候 比西耶尔
答案 0 :(得分:2)
对于您要做的事情,覆盖save
方法可能更容易,也更有效。
class Invitation(models.Model):
#other fields here
code = models.CharField(max_length=128, null=True, blank=True)
tags = models.ManyToManyField("CategorieInvitation", null=True, blank=True)
tags2 = models.ManyToManyField("Usage", null=True, blank=True)
note = models.CharField(max_length=128, null=True, blank=True)
used = models.BooleanField(default=False, blank=True)
send_to = models.EmailField(null=True, blank=True)
# a revoir
def save(self, *args, **kwargs):
if not self.code:
self.code = generate_invitation(1)[0]
super(Invitation, self).save(*args, **kwargs)
顺便说一句post_save
不应该是模型实例方法。
请参阅:https://docs.djangoproject.com/en/1.4/ref/signals/#signals