python - 需要对 Django REST Framework 中的序列化程序的 `Including extra context` 进行说明

标签 python django serialization django-rest-framework

根据:https://www.django-rest-framework.org/api-guide/serializers/#including-extra-context

我可以写:

serializer = AccountSerializer(account, context={'request': request})

然后serializer.data将如下所示:

# {'id': 6, 'owner': 'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'}

但它没有说明我如何实现它。我的意思是它必须基于对 rest_framework.reverse 的调用,有点像这个例子:

class CompleteTaskModelSerializer(rest_serializers.ModelSerializer):

    resultLocation = rest_serializers.SerializerMethodField()

    class Meta:
        model = TaskModel
        fields = ('id', 'resultLocation')

    def get_resultLocation(self, obj):
        return reverse('model', obj.model, request=request)

但它不会承认我的方法 get_resultLocation 中有任何称为 request 的内容。这个魔法如何发挥作用?

最佳答案

在同一个文档中,它还说:

The context dictionary can be used within any serializer field logic, such as a custom .to_representation() method, by accessing the self.context attribute.

所以我猜示例类可以更改为这样工作

class CompleteTaskModelSerializer(rest_serializers.ModelSerializer):

    resultLocation = rest_serializers.SerializerMethodField()

    class Meta:
        model = TaskModel
        fields = ('id', 'resultLocation')

    def get_resultLocation(self, obj):
        return reverse('model', obj.model, request=self.context['request'])

关于python - 需要对 Django REST Framework 中的序列化程序的 `Including extra context` 进行说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57924550/

相关文章:

python - 查询 OneDrive 中的文件返回空列表

django - 是否可以设置django-tastypie对象键?

python - 注册后即可获取 Facebook 好友

python - 虽然满足条件但循环不会中断(Collat​​z 序列)

python - scikit-learn pipeline (SVC) 的功能重要性

python - 在不带参数的函数中调用函数

c# - 如何从 xml 反序列化数据以及如何通过 xml 元素名称动态创建类?

python - 在python脚本中加载新安装的模块

java - java序列化如何解决循环引用问题?

java - 序列化对象解密(和其他字节字段)期间出现 StreamCorruptedException