Python Django 将整数模型字段的范围设置为约束

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33772947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:57:37  来源:igfitidea点击:

Django set range for integer model field as constraint

pythondjangodjango-models

提问by Md. Tanvir Raihan

I have a django model,

我有一个 Django 模型,

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

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

我想为qty这样的东西设置约束,>0 或 <0,即qty可以是负数或正数,但不能是 0。

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

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

采纳答案by JRodDynamite

You can use Django's built-in validators-

您可以使用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)]
     )

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 linkfor more info.

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

回答by utkbansal

You will have to create a custom validator

您将不得不创建一个自定义验证器

from django.core.exceptions import ValidationError

def validate_number(value):
    if something :  # Your conditions here
        raise ValidationError('%s some error message' % value)

And then use this validator in your model

然后在你的模型中使用这个验证器

from django.db import models

class MyModel(models.Model):
    field = models.IntegerField(validators=[validate_number])

回答by Kishan

If you are using postgres, you can use range fields to specify the range. Check this: Range Fields in django

如果您使用的是 postgres,则可以使用范围字段来指定范围。检查这个:Django 中的范围字段

回答by maerteijn

Since Django 2.2 you can enforce the constraints on a database level with CheckConstraint:

从 Django 2.2 开始,您可以使用CheckConstraint在数据库级别强制执行约束:

from django.db import models

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

    class Meta:
        constraints = [
            models.CheckConstraint(
                check=models.Q(qty__gte=1) & models.Q(qt__lte=10),
                name="A qty value is valid between 1 and 10",
            )
        ]