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

后端 未结 2 1234
猫巷女王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.

提交回复
热议问题