Search code examples
djangodjango-modelsdjango-formsdjango-validation

Django: Order of validation in Models


Recently I found out that its possible to define Django form validation directly in the models.py file. This can be done the following way:

fev1_liter = models.DecimalField(validators=[MaxValueValidator(8.2),
             MinValueValidator(0.3)], 
             max_digits=3, decimal_places=2)

This is an awesome alternative to validation in forms.py, but I do have a very annoying problem: How can I control in which order the validation is executed? In this example Django will first validate if the inputs digits is in the format x.xx and thereafter min and max value. This results in some very confusing error messages. Thanks in advance!


Solution

  • For each model field, field.clean() first performs field validation via field.validate(), then via field.run_validators(), validators are called in order they are returned from the field.validators iterator.

    This makes sense, because in the general case you can expect your validators to fail if the field validation failed, so it makes for easier debugging. Remember that field validators are non-obligatory, so field.validate() takes precedence. If you want to change the behavior, you'll have to create your own Field classes and override the field.clean() behavior.

    You can inspect the field sources for more details.