You can add SQL constraints as described here as CheckConstraints in Meta.constraints.
Combined example:
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db.models import CheckConstraint, Q
class Foo(Model):
myfloat = FloatField(min=0.0, max=1.0,
# for checking in forms
validators=[MinValueValidator(0.0), MaxValueValidator(1.0)],)
class Meta:
constraints = (
# for checking in the DB
CheckConstraint(
check=Q(myfloat__gte=0.0) & Q(myfloat__lte=1.0),
name='foo_myfloat_range'),
)
It's been quite some time and the community voted answer is good enough, based on Django built-ins, but here is another approach, problem specific, following the Django Project's documentation.
Create a custom validator
# app/models.py or create another file for custom validators, i.e. app/custom_validators.py
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _ # use if you support internationalization
def validate_interval(value):
if value < 0.0 or value > 1.0:
raise ValidationError(_('%(value)s must be in the range [0.0, 1.0]'), params={'value': value},)
Use your validator in your models
# app/models.py
class Foo(models.Model):
myfloat = models.FloatField(validators=[validate_interval])
You can even make the validator parametric to be more generic.
EDIT - IMPORTANT
Bare in mind that any validator is invoked during the form's clean() method.
I.E. if you try to directly create an object without using a form, your validator will NOT be invoked.
There are those who don't recommend it but if you want to invoke validators while creating an object override the save method.
# app/models.py
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _ # use if you support internationalization
class Foo(models.Model):
def save(self, *args, **kwargs):
self.full_clean() # or clean
super().save(*args, **kwargs)
def validate_interval(value):
if value < 0.0 or value > 1.0:
raise ValidationError(_('%(value)s must be in the range [0.0, 1.0]'), params={'value': value},)
myfloat = models.FloatField(validators=[validate_interval])