Django IntegerRangeField验证失败
问题内容:
我正在尝试为年龄范围字段实现IntegerRangeField()。不幸的是,文档没有说明如何验证上限和下限。
我从这样的模型中尝试过:
class SomeModel(models.Model):
age_range = IntegerRangeField(default='(0,100)', blank=True, validators=[MinValueValidator(1), MaxValueValidator(100)])
问题是,无论您在字段中输入什么内容,Django都会引发ValidationError:
该值必须小于或等于100
另外,如果我在该字段中未放入任何内容,则它不会放入默认范围,并且会失败,并抱怨IntegrityError。
因此,我尝试从表单对象执行此操作:
class SomeForm(forms.ModelForm):
age_range = IntegerRangeField(validators=[MinValueValidator(1), MaxValueValidator(100)])
但这根本不起作用。我在字段中输入的任何数字都会保存。我究竟做错了什么?
问题答案:
的MinValueValidator
和MaxValueValidator
是整数,所以他们是不正确的验证用在这里。而是将验证器专门用于range:RangeMinValueValidator
和RangeMaxValueValidator
。
这两个验证器都位于模块中django.contrib.postgres.validators
。
另外,IntegerRangeField
在Python中将an表示为psycopg2.extras.NumericRange
对象,因此default
在模型中指定参数时,请尝试使用an而不是字符串。
注意:NumericRange
默认情况下,对象包含下限,不包含上限,因此NumericRange(0,100)将包括0,而不包括100。您可能希望使用NumericRange(1,101)。您也可以bounds
在NumericRange
对象中指定一个参数,以更改包含/排除的默认值,以代替更改数字值。请参阅NumericRange对象文档。
例:
# models.py file
from django.contrib.postgres.validators import RangeMinValueValidator, RangeMaxValueValidator
from psycopg2.extras import NumericRange
class SomeModel(models.Model):
age_range = IntegerRangeField(
default=NumericRange(1, 101),
blank=True,
validators=[
RangeMinValueValidator(1),
RangeMaxValueValidator(100)
]
)