user3134477 user3134477 - 10 months ago 54
Python Question

Pass context from one serializer to another?

With Django REST Framework, I have 2 serializers:


depends on some extra "context" value, but it doesn't get it directly, instead it needs to get it from
, 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(
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 Source

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.