[Solved]-Extend django rest framework to allow inheriting context in nested serializers


Apparently I missed something…
The ‘context’ is already inherited down to the nested serializers…

However, the reason it didn’t work for me, is because as part of my nesting, some of the child serializers were defined via serializers.SerializerMethodField().
And in such as case (only!) the context is not automatically inherited.

The solution is to simply pass-on the ‘context’, within the ‘get_…’ method related to each SerializerMethodField:

class ParentSerializer(serializers.ModelSerializer):
    child = serializers.SerializerMethodField()

    def get_child(self, obj):
        child = ....
        serializer = ChildSerializer(instance=child, context=self.context)
        return serializer.data

P.S – a DRF github issue similar to mine was created a while ago: https://github.com/tomchristie/django-rest-framework/issues/2555


Leave a comment