I am currently creating an api based on DRF.I have a model which is like:
class Task(models.Model):
name = models.CharField(max_length = 255)
completed = models.BooleanField(default = False)
description = models.TextField()
text = models.TextField(blank = False, default = "this is my text" )
def __unicode__(self):
return self.name
and the corresponding Serializer for this model is as :
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = ('name','description','completed','text')
Now my question is that I want to validate the 'name' field of my model while taking up data. For instance I may end checking the first name or second name of the user by a Python code similar to a Django Form:
def clean_name(self):
name = form.cleaned_data.get('name')
first,second = name.split(' ')
if second is None:
raise forms.ValidationError("Please enter full name")
I know of something called 'validate_(fieldname)' in Serializers.serializer class. But I want this to be used in Serializers.ModelSerializer instead.(Just similar to the custom forms validation in Django)
You can add a validate_name()
method to your serializer which will perform this validation. It should return the validated value or raise a ValidationError
.
To perform the check whether user has entered a full name or not, we will use str.split()
which will return all the words in the string. If the no. of words in the string is not greater than 1, then we will raise a ValidationError
. Otherwise, we return the value
.
class TaskSerializer(serializers.ModelSerializer):
def validate_name(self, value):
"""
Check that value is a valid name.
"""
if not len(value.split()) > 1: # check name has more than 1 word
raise serializers.ValidationError("Please enter full name") # raise ValidationError
return value