Django 文档建议在需要通过覆盖访问多个字段的情况下进行自定义验证Model.clean()
。
文档中的这个示例显示了如何验证仍处于“草稿”阶段的新闻文章没有发布日期。
def clean(self):
import datetime
from django.core.exceptions import ValidationError
# 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
要在每次保存对象时调用它,您还需要覆盖保存方法:https ://docs.djangoproject.com/en/dev/topics/db/models/#overriding-model-methods 。
如果您只需要验证单个字段,则其他用例的另一个有用参考是编写自定义验证器:https ://docs.djangoproject.com/en/dev/ref/validators/