user3134477 user3134477 - 9 days ago 6
Python Question

Pass context from one serializer to another?

With Django REST Framework, I have 2 serializers:

PageSerializer
and
CommentSerializer
.

CommentSerializer
depends on some extra "context" value, but it doesn't get it directly, instead it needs to get it from
PageSerializer
, since they have a nested relationship.

So I need to have something like this:

class CommentSerializer(serializers.ModelSerializer):
...
my_field = serializers.SerializerMethodField()

def get_my_field(self, comment):
my_value = self.context['my_value']
...

class PageSerializer(serializers.ModelSerializer):
...
comments = CommentSerializer(
many=True,
context={'my_value': my_value} # my_value doesn't exist until __init__ is called, so I can't pass it
)

...
my_value = 1
page_serializer = PageSerializer(page, context={'my_value': my_value})


But, of course, this code can't work.

What kind of workaround can I do here?

Answer

When you define the relationship in the serializer like you did, PageSerializer's context will be automatically passed to CommentSerializer when the page's comments are serialized.

So, just defining comments = CommentSerializer(many=True) will do.