gpt4 book ai didi

python - Django REST 框架 : Customize data dict on JSONRenderer

转载 作者:行者123 更新时间:2023-11-28 17:34:06 26 4
gpt4 key购买 nike

我关注 this question这帮助我了解如何覆盖我的 JSONRenderer,但我又对如何为覆盖的 JSONRenderer 提供 arg 产生疑问,以便我可以根据需要更改我的“元素”名称:

请看下面的片段:

from rest_framework.renderers import JSONRenderer

class EmberJSONRenderer(JSONRenderer):

def render(self, data, accepted_media_type=None, renderer_context=None):
data = {'element': data}
return super(EmberJSONRenderer, self).render(data, accepted_media_type, renderer_context)

我的意图是将这个“元素”更改为我想通过 arg 获得的变量,因此我尝试了这个:

renderers.py

from rest_framework.renderers import JSONRenderer

class EmberJSONRenderer(JSONRenderer):
def __init__(self,myarg='teste'):
self.myarg = myarg

def render(self, data, accepted_media_type=None, renderer_context=None):
data = {self.myarg:data}

return super(EmberJSONRenderer, self).render(data, accepted_media_type, renderer_context)

views.py 中:

class myViewSet(viewsets.ModelViewSet):
myrender = EmberJSONRenderer(myarg='abc')
renderer_classes = (myrender, BrowsableAPIRenderer, )
queryset = mymodel.objects.filter(myfilter=2)
serializer_class = mySerializer
allowed_methods = ('GET','OPTIONS','HEAD')

这会引发以下类型错误:

'EmberJSONRenderer' object is not callable

你有什么建议我如何将信息从我的 View 直接传递给渲染器作为 arg?

最佳答案

大家好,这是我发现的一种方法here并为我工作。我没有通过我的 JSONRenderer 传递 var,而是执行了以下操作:

serializer.py中:

class mySerializer(serializers.ModelSerializer):
...

class Meta:
model = ...
service_name = 'mycustom name'
fields = ...

比我的renderer.py:

from rest_framework.renderers import JSONRenderer

class EmberJSONRenderer(JSONRenderer):

def render(self, data, accepted_media_type=None, renderer_context=None):
service_name = getattr(renderer_context.get('view').get_serializer().Meta, 'service_name', 'objects')


data = {service_name:{'name_pt':'name', 'keywords':data}}

return super(EmberJSONRenderer, self).render(data, accepted_media_type, renderer_context)

如您所见,我使用 renderer_context 通过 getattr 方法从 View 中获取信息:

getattr(renderer_context.get('view').get_serializer().Meta, 'service_name', 'objects')

关于python - Django REST 框架 : Customize data dict on JSONRenderer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32123603/

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