context in nested serializers django rest framework

后端 未结 5 2062
有刺的猬
有刺的猬 2021-01-07 16:35

If i have a nested serializer:

class ChildSerializer(ModelSerializer):
    class Meta:
        fields = (\'c_name\', )
        model = Child


class ParentSe         


        
5条回答
  •  旧巷少年郎
    2021-01-07 17:04

    Ok, I have found an ultimate solution that will do exactly what was asked - pass context down to nested serializers. To achieve that one need to override to_representation(self, instance) of the nested serializer, so it looks like:

    def to_representation(self, instance):
        # here we update current serializer's context (access it as self._context)
        # to access parent's context we use parent.context
        # if there is no parent than it's the first serializer in the chain and it doesn't need any context except for itself's
        # for example (after all the checks)
        self._context["request"] = self.parent.context["request"]
        # and that is it! The modified context will be used for serialization as if it was passed as usually
        return super().to_representation(instance)
    

提交回复
热议问题