Karthik
Karthik

Reputation: 155

How to get value of a nested serializer field from its parent serializer class?

Consider the followings two serializers:

class SerializerA(BaseSerializer):
    field_1 = serializers.IntegerField()
    field_2 = SerializerB()

class SerializerB(BaseSerializer):
    field_3 = serializers.IntegerField()

The input JSON for SerializerB will not contain field_3 and it has to obtained from field_1 of SerializerA.

I have tried this

class SerializerB(BaseSerializer):
    field_3 = serializers.IntegerField()

    def __init__(self, instance=None, data=empty, **kwargs):
        if data is not empty and isinstance(data, dict):
            _data = data.copy()
            _data['field_3'] = self.parent.initial_data.get('field_1')
            super(SerializerB, self).__init__(instance, _data, **kwargs)

        super(SerializerB, self).__init__(instance, data, **kwargs)

But it is not working as data is always empty and it never passes the if statement.

Upvotes: 0

Views: 1272

Answers (1)

OgarOgarovic
OgarOgarovic

Reputation: 115

Nested writable deserialization is not supported out of the box in Django Rest, you need to write your own create/update methods: documentation, so I think the framework is not even delegating the data to child (nested) serializers on initialization.

Another consideration is that the parent attribute of the nested serializer (SerializerB) is None in __init__, it is only getting a value in the bind method of the nested serializer. So if you want to use the self.parent.initial_data.get() construct, you need to do it in the bind method of SerializerB

Upvotes: 2

Related Questions