在实现我的api时,我希望它能够以xml格式查看。不只是JSON

时间:2019-06-14 13:44:30

标签: python django xml django-rest-framework

我正在为轮询应用程序创建一个Web api,Django为我们提供了自己的练习。我能够走得很远,但是我一直想提供一个使用xml格式化的选项。

我尝试使用DEFAULT_PARSERDEFAULT_RENDER,但实际上并没有达到我想要的方式。我只想提供一个类似JSON的选项。

这是我的api / views类

from rest_framework import generics
from . serializers import QuestionSerializer, ChoiceSerializer
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter, SearchFilter

from polls.models import Choice, Question

class QuestionList(generics.ListAPIView):
    serializer_class = QuestionSerializer
    queryset = Question.objects.all()
    filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter)
    filter_fields = {'id': ['gte', 'lte', 'exact'], 'pub_date': ['gte', 'lte']}
    ordering_fields = ('id', 'question_text', 'pub_date')
    search_fields = ('pub_date', 'question_text')


class ChoiceList(generics.ListAPIView):
    serializer_class = ChoiceSerializer
    queryset = Choice.objects.all()
    filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter)
    # trying to do greater than or less than filter fields stuff
    filter_fields = {'id': ['gte', 'lte', 'exact'], 'votes': ['gte', 'lte', 'exact']}
    ordering_fields = ('id', 'votes', 'choice_text', 'question',)
    search_fields = ('choice_text', 'question')

这是api / serializers类

from rest_framework import routers, serializers, viewsets
from polls.models import Question, Choice


#  serializer is the way you can see the list of info for the models you have selected

class QuestionSerializer(serializers.ModelSerializer):

    class Meta:
        model = Question
        fields = '__all__'

# i have no idea how to make hyperlinks to open up another page
class ChoiceSerializer(serializers.ModelSerializer):

    class Meta:
        model = Choice
        fields = ('id', 'votes', 'choice_text', 'question')

Want to be able to have a drop down menu and have it say 'XML'

1 个答案:

答案 0 :(得分:2)

将XML解析器/渲染器添加到默认值:

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
        'rest_framework_xml.renderers.XMLRenderer'
    ),
    'DEFAULT_PARSER_CLASSES': (
        'rest_framework.parsers.JSONParser',
        'rest_framework.parsers.FormParser',
        'rest_framework_xml.parsers.XMLParser'
    )
}