Assuming I have a Django model like the following:
class Comprobante(models.Model):
punto_venta = models.IntegerField(blank=True)
And I want to validate the model and particularly that punto_venta
is a value from 1 to 9999. I understand that there are two ways:
Use a validator in the field
def punto_venta_validate(value):
if not value:
raise ValidationError(_('El punto de venta es obligatorio'))
if value <1 or value > 9999:
raise ValidationError(_('El punto de venta debe debe ser un valor entre 1 y 9999'))
class Comprobante(models.Model):
punto_venta = models.IntegerField(blank=True, validators=[punto_venta_validate]))
Validate in the event clean()
of the model
def clean(self):
punto_venta_validate(self.punto_venta)
The only visible difference is that a ValidationError
when validating the field by using validators
, will display the message next to the field in the administration interface, when we use clean()
to validate, I see that the error appears on all fields. Eventually with clean()
we could also validate multiple conditions and each error add it to a list, in this way we could show all the errors of each field, so it would not be a difference between both methods either. So: What is the difference between the two methods? Is it just a matter of how the ValidationError
is shown or is there something else that is slipping away?