Sanitizing / changing input for serializer fields

783 views
Skip to first unread message

Kevin London

unread,
Apr 23, 2015, 8:25:53 PM4/23/15
to django-res...@googlegroups.com
We're using Django Rest Framework and, in some cases, adjusting the values of the input provided to the serializer based on some other criteria. We're currently doing that in the `validate_field` methods on the serializer and it feels wrong. I'm wondering if there's a better way to approach the problem. For example:

class ExampleSerializer(Serializer):

   name
= serializers.CharField()
   is_active
= serializers.BooleanField()

   
. . .

   
def validate_name(self, value):
       name
= self.sanitize_input(name)
       
if not name:
           
raise ValidationError()
       
return name

   
def validate(self, attrs):
       
if attrs['name'] and not attrs['is_active']:
           attrs
['is_active'] = True

       
return attrs

This is just an example, of course we wouldn't have quite this combination of fields / logic. Is there a better place to do these things like this? Are we approaching it in the wrong way? 

Chris Foresman

unread,
Apr 24, 2015, 11:16:42 AM4/24/15
to django-res...@googlegroups.com
No, this is pretty much the best way to do it. 

One thing that's not always obvious is that if you're in a view method that uses an existing object, you can access that object via self.instance. So if you're updating an existing instance, you can set values of field in validate_field(self, value) like so:

class ExampleSerializer(Serializer):

   name
= serializers.CharField()
   is_active
= serializers.BooleanField()

   
. . .

   
def validate_is_active(self, value):
       
if self.instance is not None and self.instance.name:
           
return True
       
return value

   
def validate_name(self, value):

       name
= self.sanitize_input(name)
       
if not name:
           
raise ValidationError()
       
return name

   
def validate(self, attrs):
       
if attrs['name'] and not attrs['is_active']:
           attrs
['is_active'] = True

       
return attrs
Reply all
Reply to author
Forward
0 new messages