Django Rest Framework更改根项和列表项元素名称

时间:2017-11-22 11:34:16

标签: python django rest django-rest-framework django-rest-viewsets

我是Django-Rest框架的新手。我想根据模型名称更改root和list-item元素名称:

自:

<root>
    <list-item>worrier1</list-item>
    <list-item>worrier2</list-item>
<root>

要:

<tests>
    <test>worrier1</test>
    <test>worrier2</test>
<tests>

我已根据answer from here覆盖了XMLRenderer,但我不确定如何将此路由到我的视图。

我的观点:

class SampleViewSet(viewsets.ModelViewSet):

    myrenderer = ModifiedXMLRenderer(item_tag="tests", root_tag="test")

    queryset = Sample.objects.all()
    serializer_class = SampleSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]

ModifiedXMLRenderer:

class ModifiedXMLRenderer(XMLRenderer):


    def __init__(self, item_tag=None,root_tag=None):
        self.item_tag_name = item_tag or "item"
        self.root_tag_name = root_tag or "channel"

    def render(self, data, accepted_media_type=None, renderer_context=None):
        """
        Renders `data` into serialized XML.
        """
        if data is None:
            return ''

        stream = StringIO()

        xml = SimplerXMLGenerator(stream, self.charset)
        xml.startDocument()
        xml.startElement(self.root_tag_name, {})

        self._to_xml(xml, data)

        xml.endElement(self.root_tag_name)
        xml.endDocument()
        return stream.getvalue()

    def _to_xml(self, xml, data):
        if isinstance(data, (list, tuple)):
            for item in data:
                xml.startElement(self.item_tag_name, {})
                self._to_xml(xml, item)
                xml.endElement(self.item_tag_name)

        elif isinstance(data, dict):
            for key, value in six.iteritems(data):
                xml.startElement(key, {})
                self._to_xml(xml, value)
                xml.endElement(key)

        elif data is None:
            # Don't output any value
            pass

        else:
            xml.characters(force_text(data))

1 个答案:

答案 0 :(得分:0)

我们可以通过覆盖方法get_renderers来实现它。

class SampleViewSet(viewsets.ModelViewSet):
   queryset = Sample.objects.all()
   serializer_class = SampleSerializer
   permission_classes = [IsAuthenticatedOrReadOnly]

   def get_renderers(self):
      return [ModifiedXMLRenderer(item_tag="tests", root_tag="test")]