序列化程序 - 在 Django Rest Framework 3 中包含额外的上下文不起作用

tsa*_*tor 2 django-rest-framework

该文件指出:

您可以通过context在实例化序列化程序时传递参数来提供任意附加上下文。

好的,让我们这样做:

serializer = AccountSerializer(account, context={'foo':'bar'})
Run Code Online (Sandbox Code Playgroud)

然后文档指出:

通过访问self.context属性,可以在任何序列化器字段逻辑中使用上下文字典。

好的,让我们这样做:

class AccountSerializer(serializers.ModelSerializer):

    custom_field = serializers.SerializerMethodField()

    class Meta:
        model = Account
        fields = ('id', 'name', 'custom_field')

    def get_custom_field(self, obj):
        print('Context:', self.context)
        foo = self.context.get('foo')
        print('Foo:', foo)
        ...
        return "custom data"
Run Code Online (Sandbox Code Playgroud)

这些打印语句导致:

Context: {'request': <rest_framework.request.Request object at 0x1127d3160>, 'format': None, 'view': <account.api.views.AccountView object at 0x1127c4f98>

Foo: None
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么?无论上下文是什么,都不会使用所需的额外上下文进行修改。

Lin*_*via 5

您正在显示DRF GenericAPIView 中使用的序列化程序的结果。所述get_serializer_context默认方法提供的上下文条目“请求”,“查看”和“格式”和串行构造的上下文参数是无效的。如果要在上下文中添加更多内容,还需要在视图中覆盖它:

def get_serializer_context(self):
    context = super().get_serializer_context()
    context['foo'] = 'bar'
    return context
Run Code Online (Sandbox Code Playgroud)