How to limit the maximum value of a numeric field in a Django model?

后端 未结 6 1583
醉话见心
醉话见心 2020-11-27 09:56

Django has various numeric fields available for use in models, e.g. DecimalField and PositiveIntegerField. Although the former can be restricted to the number of decimal pla

6条回答
  •  醉酒成梦
    2020-11-27 10:28

    You can use Django's built-in validators—

    from django.db.models import IntegerField, Model
    from django.core.validators import MaxValueValidator, MinValueValidator
    
    class CoolModelBro(Model):
        limited_integer_field = IntegerField(
            default=1,
            validators=[
                MaxValueValidator(100),
                MinValueValidator(1)
            ]
         )
    

    Edit: When working directly with the model, make sure to call the model full_clean method before saving the model in order to trigger the validators. This is not required when using ModelForm since the forms will do that automatically.

提交回复
热议问题