在 Django 的字段中添加额外的约束 [英] Adding extra constraints into fields in Django

查看:27
本文介绍了在 Django 的字段中添加额外的约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在子类化 db.models.Model 时,有时必须添加额外的检查/约束.

While subclassing db.models.Model, sometimes it's essential to add extra checks/constraints.

例如我有一个带有 start_dateend_dateEvent 模型.

E.g. I have an Event model with start_date and end_date.

我想在字段或模型中添加验证,以便 end_date >开始日期.

I want to add validation into the fields or the model so that end_date > start_date.

有多少种可能的方法来做到这一点?

How many possible ways to do this?

至少我知道这可以在 ModelForm 验证内部的 models.Model 之外完成.

At least I know this can be done outside the models.Model inside the ModelForm validation.

但是如何附加到字段和models.Model?

But how to attach to the fields and the models.Model?

推荐答案

我不会在 save 方法中放置这样的约束,为时已晚.在那里引发异常对以错误方式输入数据的用户没有帮助,因为它最终会变成 500 并且用户不会得到带有错误等的表单.

I would not put constraints like these in the save method, it's too late. Raising an exception there, doesn't help the user who entered the data in the wrong way, because it will end up as a 500 and the user won't get the form with errors back etc.

你真的应该在 Forms/ModelForms clean 方法中检查这个并引发一个 ValidationError,所以 form.is_valid() 返回 false,你可以将表单中的错误发送回给用户更正.

You should really check for this in the Forms/ModelForms clean method and raise a ValidationError, so form.is_valid() returns false and you can send the errors in the form back to the user for correction.

另请注意,从 1.2 版开始,Django 已经有了模型验证.

Also note that since version 1.2, Django has had Model Validation.

它看起来像这样:

class Foo(models.Model):
    #  ... model stuff...
    def clean(self):
        if self.start_date > self.end_date:
            raise ValidationError('Start date is after end date')

这篇关于在 Django 的字段中添加额外的约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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