How to create a Django FloatField with maximum and minimum limits?

后端 未结 2 1232
猫巷女王i
猫巷女王i 2020-12-23 13:00

I\'m storing some floating-point data in my Django models, and only a certain range of values are meaningful. Therefore, I\'d like to impose these limits at both the model a

相关标签:
2条回答
  • 2020-12-23 13:45

    The answers so far describe how to make forms validate. You can also put validators in the model. Use MinValueValidator and MaxValueValidator.

    For example:

    from django.core.validators import MaxValueValidator, MinValueValidator
    
    ...
    weight = models.FloatField(
        validators=[MinValueValidator(0.9), MaxValueValidator(58)],
    )
    

    I don't think that adds SQL constraints, tho.

    0 讨论(0)
  • 2020-12-23 13:49

    If you need constraint on form level you can pass min_value and max_value to form field:

    myfloat = forms.FloatField(min_value=0.0, max_value=1.0)
    

    But if you need to move it up to model level you have to extend base models.FloatField class

    class MinMaxFloat(models.FloatField):
        def __init__(self, min_value=None, max_value=None, *args, **kwargs):
            self.min_value, self.max_value = min_value, max_value
            super(MinMaxFloat, self).__init__(*args, **kwargs)
    
        def formfield(self, **kwargs):
            defaults = {'min_value': self.min_value, 'max_value' : self.max_value}
            defaults.update(kwargs)
            return super(MinMaxFloat, self).formfield(**defaults)
    

    Then you can use it in models

    class Foo(models.Model):
        myfloat = MinMaxFloat(min_value=0.0, max_value=1.0)
    
    0 讨论(0)
提交回复
热议问题