添加自定义 Django 模型验证 [英] Adding Custom Django Model Validation
问题描述
我有一个带有开始和结束日期范围的 Django 模型.我想强制验证,以便没有两条记录具有重叠的日期范围.实现此目的的最简单方法是什么,这样我就不必重复编写此逻辑?
I have a Django model with a start and end date range. I want to enforce validation so that no two records have overlapping date ranges. What's the simplest way to implement this so that I don't have to repeat myself writing this logic?
例如我不想在一个表单和一个ModelForm
和一个管理表单和中重新实现这个逻辑模型的覆盖 save()
.
e.g. I don't want to re-implement this logic in a Form and a ModelForm
and an admin form and the model's overridden save()
.
据我所知,Django 并没有让全局强制执行这些类型的标准变得容易.
As far as I know, Django doesn't make it easy to globally enforce these types of criteria.
谷歌搜索并不是很有帮助,因为模型验证"通常是指验证特定的模型字段,而不是整个模型内容或字段之间的关系.
Googling hasn't been very helpful, since "model validation" typically refers to validating specific model fields, and not the entire model contents, or relations between fields.
推荐答案
我发现有用的基本模式是将我所有的自定义验证放在 clean()
中,然后简单地调用 full_clean()
(调用 clean()
和其他一些方法)从 save()
内部,例如:
The basic pattern I've found useful is to put all my custom validation in clean()
and then simply call full_clean()
(which calls clean()
and a few other methods) from inside save()
, e.g.:
class BaseModel(models.Model):
def clean(self, *args, **kwargs):
# add custom validation here
super().clean(*args, **kwargs)
def save(self, *args, **kwargs):
self.full_clean()
super().save(*args, **kwargs)
默认情况下不会执行此操作,如此处所述,因为它会干扰某些功能,但这些对我的应用程序来说不是问题.
This isn't done by default, as explained here, because it interferes with certain features, but those aren't a problem for my application.
这篇关于添加自定义 Django 模型验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!