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.
If you only want it to be 'A', 'B', and 'C', you should definitely use Django's built in validation instead of rolling your own. See https://docs.djangoproject.com/en/1.3/ref/models/fields/ in the section titled choices
.
In brief:
class Action(models.Model):
"""
Contains the logic for the visit
"""
TO_CHOICES = (
(0, 'Choice 0'),
(1, 'Choice 1'),
(2, 'Choice 2'),
)
id = models.AutoField(primary_key=True)
path = models.CharField(max_length=65535, null=False)
to = models.IntegerField(null=False, choices=TO_CHOICES)
In the example you gave, I would use the choice
parameter. If you put the validation for to
field in the clean method, then any errors will be associated with the action instance and not the to
field.
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.
from django.core.exceptions import ValidationError
def validate_to(value):
"""
Ensure that the 'to' is either 1, 2 or 3.
"""
if value not in [1, 2, 3]:
raise ValidationError("Invalid 'to' value.")
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,validators=[validate_to])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.