【问题标题】:Django IntegerRangeField Validation failingDjango IntegerRangeField 验证失败
【发布时间】:2015-04-05 17:46:11
【问题描述】:

我正在尝试为年龄范围字段实现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)])

但这根本没有任何作用。我在字段中输入的任何数字都会保存。我做错了什么?

【问题讨论】:

  • 试试这个并告诉我会发生什么:age_range = IntegerRangeField(lower=1, upper=100, bounds="[]")我从这里的 psycopg2 文档中得到它initd.org/psycopg/docs/extras.html#psycopg2.extras.NumericRange
  • django IntegerRangeField 文档提到它继承自 psycopg2 中的 NumericRange 字段,不要忘记这些是 PostgreSQL 特定字段,请确保您使用的是 PostgreSQL 数据库。
  • @HassenPy 这实际上是我在模型中尝试的第一件事。没用。 Django 甚至不会迁移,说它们是意想不到的关键字。
  • 就我个人而言,我不会使用一个记录不充分的功能,它实际上缺乏有关如何实现的资源,请尝试创建自己的自定义字段,这可能会让您感兴趣 stackoverflow.com/questions/849142/…

标签: python django postgresql


【解决方案1】:

MinValueValidatorMaxValueValidator 用于整数,因此在此处使用它们是不正确的验证器。而是使用专门针对范围的验证器:RangeMinValueValidatorRangeMaxValueValidator

这两个验证器都位于模块 django.contrib.postgres.validators

Here is a link 到验证器源代码。

此外,IntegerRangeField 在 Python 中表示为 psycopg2.extras.NumericRange 对象,因此当您在模型中指定 default 参数时,请尝试使用它而不是字符串。

注意:NumericRange 对象默认包含下限但不包含上限,因此 NumericRange(0, 100) 将包括 0 而不包括 100。您可能需要 NumericRange(1, 101)。您还可以在 NumericRange 对象中指定 bounds 参数来更改包含/排除的默认值,而不是更改数值。见the NumericRange object documentation

例子:

# 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)
        ]
    )

【讨论】:

  • 这成功了!我查看了所有 contrib.postgres 文件,但一定错过了这个。谢谢。 NumericRange 注释也很有帮助,尽管我以前的方法似乎也有效。
猜你喜欢
  • 2012-09-08
  • 2015-06-02
  • 1970-01-01
  • 2022-01-11
  • 2017-03-29
  • 2011-06-14
相关资源
最近更新 更多