Hi Django Developers,
I'm new to contributing and from what I gathered, I should ask here before opening a ticket.
Right now the way to validate a model as a whole is to override Model.clean(). I have 2 problems with this:
1) If you do multiple checks that raise ValidationErrors, it is tedious to accumulate them.
2) Having different models that checks almost the same, e.g. start_date should come before end_date, it should be easy to reuse validators.
I suggest to add a 'validators' option to Model Meta options.
This should be very similar to the 'validators' option a Field has, a list of callables that raises ValidationErrors, except these should take an object 'instance' instead of a 'value'.
It should then be Model.full_clean() responsibility to call these model validators in addition to what it already does.
A concern I have is the confusion that may rise between these new 'model validators' and regular 'field validators'. Maybe clever naming could help distinguish them from eachother, and maybe it's not a huge deal since they are so closely related.
It would be nice if some common model validators got built-in as well. For example a ComparisonModelValidator could take the names of two fields and validate if they are in the right order, it could look like
class ComparisonModelValidator(low, high, message=None, code=None)
* low - field name of the lesser field
* high - field name of the greater field
* message - if not None, overrides message
* code - if not None, overrides code
Then it could be used in the model as
class Event(models.Model):
start_date = models.DateField()
end_date = models.DateField()
...
class Meta:
validators = [ComparisonModelValidator('start_date', 'end_date')]
All feedback is appreciated.
Mathias