Search code examples
pythondjangodjango-rest-frameworkdjango-serializer

Django serializers: Why source argument in does not work?


I have the following Serializer in my Django project:

class MySerializer(serializers.Serializer):
    CheckList1 = serializers.CharField(source='source_field', default="pass")

I use it for data validation, like this:

input_serializer = MySerializer(data=request.data)
input_serializer.is_valid(raise_exception=True)

The source argument seems to be not working. I pass there the request data that looks like this:

request.data = {
   source_field = "Failed"
}

when I print input_serializer.data the value of CheckList1 is pass. Does anybody know why?


Solution

  • Use .validated_data attribute.

    Hope this example helps you to do so,

    class Foo(serializers.Serializer):
        foo = serializers.CharField(source='bar')
    
    
    input_data = {
        'foo': 'this data is for foo',
        'bar': 'this data is for bar'
    }
    
    f = Foo(data=input_data)
    f.is_valid(True)
    
    print('f.validated_data', dict(f.validated_data))
    # f.validated_data {'bar': 'this data is for foo'}
    print('f.data', f.data)
    # f.data {'foo': 'this data is for foo'}