将上下文从一个串行器传递到另一个? [英] Pass context from one serializer to another?

查看:38
本文介绍了将上下文从一个串行器传递到另一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Django REST Framework,我有2个序列化程序: PageSerializer CommentSerializer .

With Django REST Framework, I have 2 serializers: PageSerializer and CommentSerializer.

CommentSerializer 依赖于一些额外的"context"值,但是它不能直接获取,而是需要从 PageSerializer 获取它,因为它们具有嵌套关系.

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?

推荐答案

像您一样在序列化程序中定义关系时, PageSerializer 的上下文将自动传递给 CommentSerializer 序列化页面的注释时.

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.

因此,只需定义 comments = CommentSerializer(many = True)即可.

这篇关于将上下文从一个串行器传递到另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆