To limit the maximum value of a numeric field in a Python Django model, we can use MaxValueValidator
and MinValueValidator
.
For instance, we write
from django.db.models import IntegerField, Model
from django.core.validators import MaxValueValidator, MinValueValidator
class CoolModel(Model):
limited_integer_field = IntegerField(
default=1,
validators=[
MaxValueValidator(100),
MinValueValidator(1)
]
)
to add the limited_integer_field
field into the CoolModel
model.
We limit the value of limited_integer_field
saved by calling MaxValueValidator
with 100 to set the max limited_integer_field
value to 100.
And we call MinValueValidator
with 1 to set the min limited_integer_field
to 1.