Django REST Framework CSV
djangorestframework-csv provides tools to integrate CSV rendering and parsing into Django REST Framework APIs. It enables DRF serializers to output data as CSV and allows DRF parsers to consume CSV data. The current version is 3.0.2, with releases tending to be driven by Django and DRF compatibility updates rather than a fixed cadence.
Warnings
- breaking Python 2 support was completely removed in version 3.0.0. Projects using older Python versions must upgrade to Python 3.
- gotcha Ensure compatibility with your Django and Django REST Framework versions. Version 3.0.0 and above officially support Django 2.x, 3.x, 4.x and DRF 3.x. Older `djangorestframework-csv` versions might have narrower compatibility ranges.
- gotcha When rendering CSV, the default headers are automatically derived from dictionary keys or serializer fields. To specify custom headers or control field order, set the `header` attribute on your `CSVRenderer` subclass, or dynamically provide headers via `renderer_context={'header': ['field_a', 'field_b']}`.
- gotcha For very large datasets, using `CSVRenderer` can consume significant memory as it loads all data into memory before rendering. Use `CSVStreamingRenderer` instead to stream data, which reduces memory footprint and improves performance for large exports.
Install
-
pip install djangorestframework-csv
Imports
- CSVRenderer
from rest_framework_csv.renderers import CSVRenderer
- CSVStreamingRenderer
from rest_framework_csv.renderers import CSVStreamingRenderer
- CSVParser
from rest_framework_csv.parsers import CSVParser
Quickstart
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_csv.renderers import CSVRenderer
class ProductListView(APIView):
renderer_classes = (CSVRenderer, )
def get(self, request, *args, **kwargs):
# In a real application, this would come from a database query
# or a DRF serializer output.
products = [
{'id': 1, 'name': 'Laptop', 'price': 1200.00},
{'id': 2, 'name': 'Mouse', 'price': 25.00},
{'id': 3, 'name': 'Keyboard', 'price': 75.00}
]
return Response(products)
# To integrate this, you would typically add it to a Django URLconf, e.g.:
# from django.urls import path
# urlpatterns = [
# path('products.csv', ProductListView.as_view(), name='product-csv'),
# ]
# When accessing /products.csv, the API will return CSV data.