In my model I have a field which should contain only the values ‘A’, ‘B’ and ‘C’. Would this be best use for using a choice parameter when declaring the field?
If I didn’t decide to use the choice parameter and wanted to write custom validation logic for it, where would I write this — would this be in the clean method of the model? I’ve also seen clean_<fieldname> methods — what are these for or doe they only apply to forms? I would like to do this validation in the model as I’m not using a form.
class Action(models.Model):
"""
Contains the logic for the visit
"""
id = models.AutoField(primary_key=True)
path = models.CharField(max_length=65535, null=False)
to = models.IntegerField(null=False)
def clean(self, **kwargs):
"""
Custom clean method to do some validation
"""
#Ensure that the 'to' is either 1,2 or 3.
if self.to not in [0, 1, 2]:
raise ValidationError("Invalid to value.")
When I’m doing validation, do I need to return some value? Will my method method be called when someone creates a new record?
(Although I’ve read the docs, I’m still a little confused about this.)
Thanks a ton.
In the example you gave, I would use the
choiceparameter. If you put the validation fortofield in the clean method, then any errors will be associated with the action instance and not thetofield.As you stated,
clean_<fieldname>methods are for form fields. On the model, you can define validators.Here’s an example of your clean method rewritten as a validator.