Pass context from one serializer to another?

谁说我不能喝 提交于 2021-02-19 02:35:09

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/40845706/pass-context-from-one-serializer-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!