0

我想知道如何控制模型数据中的转换。我在如何检查 Django (django-admin) 中的值转换?但是当我试图在我的代码中实现它时,出了点问题(我可以不受惩罚地改变状态):

这是我的代码的相关部分:

# Blog Entry Draft Status Constants
ENTRY_STATUS_DRAFT = 0
ENTRY_STATUS_PUBLISHED = 1

# Create your models here.
class Blog(models.Model):
    title = models.CharField(max_length=200, unique=True)
    body_html = models.TextField(blank=True)
    pub_date = models.DateTimeField ('Date Published', blank=True, null=True, editable=False)
    PUB_STATUS = (
        (ENTRY_STATUS_DRAFT, 'Draft'),
        (ENTRY_STATUS_PUBLISHED, 'Published'),
    )
    status = models.IntegerField(choices=PUB_STATUS, default=0)

    def clean(self):
        # Don't allow draft entries to have a pub_date.
        if self.status == 'draft' and self.pub_date is not None:
            raise ValidationError('Draft entries may not have a publication date.')
        # Set the publication date for published items if it hasn't been set already
        if self.status == ENTRY_STATUS_PUBLISHED and not self.pub_date:
            self.pub_date = datetime.datetime.now()

    def clean_status(self):
        status = self.cleaned_data.get('status')
        if status == ENTRY_STATUS_DRAFT:
            if self.instance and self.instance.status == ENTRY_STATUS_PUBLISHED:
                raise ValidationError('You cannot change published to draft')
        return status

clean() 方法有效。我还尝试在 clean_status() 方法中使用 'Published' 和 'Draft' ,但这不起作用。

我是否将 clean_status 放在正确的位置?我忽略了什么吗?

4

1 回答 1

0

您的 clean 方法应该self.cleaned_dataclean_status返回self.cleaned_data['status']. :)

于 2010-08-23T20:27:17.747 回答