Django 将整数模型字段的范围设置为约束 [英] Django set range for integer model field as constraint

查看:28
本文介绍了Django 将整数模型字段的范围设置为约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 django 模型,

I have a django model,

class MyModel(models.Model)
    qty = model.IntegerField()

我想为 qty 设置约束的地方,>0 或 <0,即 qty 可以是负数或正数,但不能为 0.

where I want to set constraint for qty something like this, >0 or <0,i.e the qty can be negative or positive but can not be 0.

在 Django 中有什么直接的方法可以做到这一点吗?

Is there any straight forward way to do this in Django?

推荐答案

您可以使用 Django 的内置验证器 -

from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator

class MyModel(models.Model):
    qty = models.IntegerField(
        default=1,
        validators=[MaxValueValidator(100), MinValueValidator(1)]
     )

注意:当您保存模型时,验证器不会自动运行,但如果您使用的是 ModelForm,它将在表单中包含的字段上运行您的验证器.查看此链接了解更多信息.

NOTE: The validators will not run automatically when you save a model, but if you are using a ModelForm, it will run your validators on the fields that are included in the form. Check this link for more info.

这篇关于Django 将整数模型字段的范围设置为约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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