添加自定义Django模型验证 [英] Adding Custom Django Model Validation

查看:84
本文介绍了添加自定义Django模型验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有开始和结束日期范围的Django模型。我想强制执行验证,以便两个记录没有重叠的日期范围。实现这一点的最简单的方法是什么,所以我不必重复自己写这个逻辑。



我不想在Form 一个 ModelForm 一个管理表单中重新实现这个逻辑>和模型被覆盖的 save()



据我所知,Django没有'使全球实施这些类型的标准变得容易。



Google搜索并没有非常有帮助,因为模型验证通常是指验证特定的模型字段,而不是整个模型内容或字段之间的关系。 p>

解决方案

我发现有用的基本模式是将所有我的自定义验证放在 clean()然后只需调用 full_clean() (调用 clean()等几种方法) code> save(),例如:

  class BaseModel(models.Model) 

def clean(self,* args,** kwargs):
#add custom validation here
super(BaseModel,self).clean(* args,** kwargs)

def save(self,* args,** kwargs):
self.full_clean()
super(BaseModel,self).save(* args,** kwargs)

这是默认情况下没有完成的,如这里所述,因为它干扰某些功能,但这些功能对我的应用程序来说不是问题。


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?

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

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.

解决方案

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(BaseModel, self).clean(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.full_clean()
        super(BaseModel, self).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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆