10

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)

Rahul
  • 2,580
  • 1
  • 20
  • 24

1 Answers1

18

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
Zubair Alam
  • 8,739
  • 3
  • 26
  • 25
Rahul Gupta
  • 46,769
  • 10
  • 112
  • 126
  • Is there anything similar to cleaned_data in serializers? – Rahul Nov 17 '15 at 04:27
  • 2
    Yes, there exists `serializer.validated_data` which is accessible after `.is_valid()` has been called on the serializer. – Rahul Gupta Nov 17 '15 at 06:02
  • 2
    You can also use `validators` parameter in a field in model class, DRF will make use that as well. Helpful in enforcing a global validation. This answer is correct as well. – Saurabh Kumar Nov 18 '15 at 05:50