0

这是我的代码:

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()

如果 Code 为空白或 null,即使在 django-admin 界面中创建,如何将 Code 替换为 generate_invitation 的结果?

问候比西尔

4

1 回答 1

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

于 2012-04-06T17:13:47.670 回答