Django模型日期时间字段

时间:2014-03-05 19:43:36

标签: django django-models

我想创建一个模型,它应该只接受今天15天后的日期并存储开始和结束时间,并在我们输入开始时间之前的结束时间时显示错误。

1 个答案:

答案 0 :(得分:0)

模型清洁功能正是您所需要的。

这是一个从django文档开始的例子:

import datetime
from django.core.exceptions import ValidationError
from django.db import models

class Article(models.Model):
    ...
    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 pub_date for published items if it hasn't been set already.
        if self.status == 'published' and self.pub_date is None:
            self.pub_date = datetime.date.today()

有关详细信息,请参阅此处:https://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects