Returning CSV format from django-rest-framework?

前端 未结 4 2188
囚心锁ツ
囚心锁ツ 2021-02-13 22:23

I have a working Django 1.8 site, and I want to add a RESTful API using django-rest-framework. I would like to support rendering to CSV and JSON formats, and am puzzling over ho

4条回答
  •  深忆病人
    2021-02-13 23:14

    This is an old post, but I've seen the accepted answer sets the CSVRenderer as one of the defaults, which is not usually wanted.

    I would implement the view this way:

    ...
    from rest_framework.viewsets import ModelViewSet
    from rest_framework.settings import api_settings
    from rest_framework_csv.renderers import CSVRenderer
    from .... import OrgSerializer
    ...
    
    class OrganizationViewSet(ModelViewSet):
    
        queryset = Organisation.objects.all()
        http_method_names = ['get', '...list all the other verbs you want']
        serializer_class = OrgSerializer
        renderer_classes = tuple(api_settings.DEFAULT_RENDERER_CLASSES) + (CSVRenderer,)
    
        def get_queryset(self):
            if 'code' in self.request.GET:
                code = self.request.GET['code']
                return Organisation.objects.filter(code=code)
            return Organisation.objects.all()
    

    Of course, having the django-rest-framework-csv installed and OrgSerializer defined somewhere.

    Then you can just set 'rest_framework.renderers.JSONRenderer' as your default renderer in settings and the rest framework will automatically return csv content if you request it on the HTTP_ACCEPT header - just for this view.

提交回复
热议问题