Django IntegerRangeField Validation failing

前端 未结 1 968
说谎
说谎 2021-01-13 03:18

I\'m trying to implement the IntegerRangeField() for an age range field. Unfortunately the documentation doesn\'t say how to validate the upper and lower bounds.

I t

1条回答
  •  孤城傲影
    2021-01-13 03:50

    The MinValueValidator and MaxValueValidator are for integers, so they are the incorrect validators to use here. Instead use the validators specifically for ranges: RangeMinValueValidator and RangeMaxValueValidator.

    Both of those validators live in the module django.contrib.postgres.validators.

    Here is a link to the validator source code.

    Also, an IntegerRangeField is represented in Python as a psycopg2.extras.NumericRange object, so try using that instead of a string when you specify your default parameter in the model.

    Note: The NumericRange object by default is inclusive of the lower bound and exclusive of the upper bound, so NumericRange(0, 100) would include 0 and not include 100. You probably want NumericRange(1, 101). You can also specify a bounds parameter in your NumericRange object to change the defaults for inclusion/exclusion, in lieu of changing the number values. See the NumericRange object documentation.

    Example:

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

    0 讨论(0)
提交回复
热议问题