Returning CSV format from django-rest-framework?

前端 未结 4 2185
囚心锁ツ
囚心锁ツ 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:13

    Got it. The trick is to install djangorestframework-csv, then add the following in settings:

    REST_FRAMEWORK = {
        'DEFAULT_RENDERER_CLASSES': (
            'rest_framework.renderers.JSONRenderer',
            'rest_framework.renderers.BrowsableAPIRenderer',
            'rest_framework_csv.renderers.CSVRenderer',
        ),
    }
    

    And then scrap the JSONResponse function in views.py and just do return Response(serializer.data) instead. Very easy in the end.

提交回复
热议问题