gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:16:23 24 4
gpt4 key购买 nike

根据: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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com