You can use Django’s built-in validators –
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
class MyModel(models.Model):
qty = models.IntegerField(
default=1,
validators=[MaxValueValidator(100), MinValueValidator(1)]
)
NOTE:
- The validators will not run automatically when you save a model, but if you are using a ModelForm, it will run your validators on the fields that are included in the form. Check this link for more info.
- To enforce constraints on a database level refer to maertejin’s answer below.