Django在模型中提供了各种数字字段,例如DecimalField和PositiveIntegerField。虽然前者可以被限制为存储小数点后的位数和存储的字符总数,但是否有办法将其限制为仅存储某个范围内的数字,例如0.0-5.0 ?
如果做不到这一点,有没有办法限制PositiveIntegerField只存储,例如,最多50的数字?
更新:现在Bug 6845已经关闭,这个StackOverflow问题可能是没有意义的。——sampablokuper
Django在模型中提供了各种数字字段,例如DecimalField和PositiveIntegerField。虽然前者可以被限制为存储小数点后的位数和存储的字符总数,但是否有办法将其限制为仅存储某个范围内的数字,例如0.0-5.0 ?
如果做不到这一点,有没有办法限制PositiveIntegerField只存储,例如,最多50的数字?
更新:现在Bug 6845已经关闭,这个StackOverflow问题可能是没有意义的。——sampablokuper
当前回答
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
size = models.IntegerField(validators=[MinValueValidator(0),
MaxValueValidator(5)])
其他回答
在forms.py中
Class FloatForm(forms.ModelForm):
class Meta:
model = Float
fields = ('name','country', 'city', 'point', 'year')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['point'] = forms.FloatField(max_value=100, min_value=1)
你可以使用Django内置的验证器-
from django.db.models import IntegerField, Model
from django.core.validators import MaxValueValidator, MinValueValidator
class CoolModelBro(Model):
limited_integer_field = IntegerField(
default=1,
validators=[
MaxValueValidator(100),
MinValueValidator(1)
]
)
编辑:当直接使用模型时,请确保在保存模型之前调用模型full_clean方法,以便触发验证器。在使用ModelForm时,这不是必需的,因为表单将自动执行此操作。
在models.py中的model列中添加如下验证器
class Planogram(models.Model):
camera = models.ForeignKey(Camera, on_delete=models.CASCADE)
xtl = models.DecimalField(decimal_places=10, max_digits=11,validators=[MaxValueValidator(1),MinValueValidator(0)])
如果你使用create函数来创建对象,将其更改为如下....的构造函数 并在该对象上调用fullclean(),然后保存.. 一切都会完美无缺。
planogram = Planogram(camera_id = camera,xtl=xtl,ytl=ytl,xbr=xbr,ybr=ybr,product_id=product_id)
planogram.full_clean()
planogram.save()
有两种方法。一种是使用表单验证,不允许用户输入任何超过50的数字。表单验证文档。
如果流程中没有用户参与,或者没有使用表单输入数据,那么必须重写模型的save方法来抛出异常或限制进入字段的数据。
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
size = models.IntegerField(validators=[MinValueValidator(0),
MaxValueValidator(5)])