rhoward
rhoward

Reputation: 191

Serializer field 'source' argument does not work when validating

Why does 'source' not work when trying to validate data?

from rest_framework import serializers

class Test(serializers.Serializer):
    my_field = serializers.CharField(source='myField')
    
test_data = {'myField': 'test1', 'myOtherField': 'test2'}

Test(test_data).data

The output: {'my_field': 'test1'}.

Test(test_data).is_valid(raise_exception=True)

The output: AssertionError: Cannot call .is_valid() as no data= keyword argument was passed when instantiating the serializer instance.

Test(data=test_data).is_valid(raise_exception=True)

The output: ValidationError: {'my_field': [ErrorDetail(string='This field is required.', code='required')]}

Upvotes: 5

Views: 1576

Answers (1)

AminAli
AminAli

Reputation: 142

Actually, you should set myField instead of serializer field and set source to my_field (The name you want your field to have).

I gave you an example here:


In serializers.py:

from rest_framework import serializers

class TestSerializer(serializers.Serializer):
    TestField = serializers.CharField(source="test_field")

In views.py:

from rest_framework.views import APIView, Response
from .serializers import TestSerializer

class TestView(APIView):
    def get(self, request):
        test_data = {"TestField": "This is a test value"}
        
        serializer = TestSerializer(data=test_data)
        serializer.is_valid(raise_exception=True)

        print(serializer.validated_data)
        return Response(serializer.validated_data)

The output of this serializer is:

>>> OrderedDict([('test_field', 'This is a test value')])

More about source attributes: https://www.django-rest-framework.org/api-guide/fields/#source

Upvotes: 4

Related Questions