Full answer
Naive exports build the whole file: HttpResponse with a csv.writer and every row in memory, or a list of 500,000 model objects. That risks memory exhaustion and request timeouts.
Streaming pattern:
class Echo:
def write(self, value):
return value # csv.writer calls write(); we return the line instead of storing it
def export(request):
writer = csv.writer(Echo())
def rows():
yield writer.writerow(["roll_no", "name"])
for s in Student.objects.values_list("roll_no", "name").iterator(chunk_size=2000):
yield writer.writerow(s)
response = StreamingHttpResponse(rows(), content_type="text/csv")
response["Content-Disposition"] = 'attachment; filename="students.csv"'
return responseWhy each part matters:
values_list(...)skips model instance creation (cheaper);iterator(chunk_size=...)avoids caching the whole result in the QuerySet. On PostgreSQL it uses server-side cursors, unless connection pooling in transaction mode (pgbouncer) forbids them: then setDISABLE_SERVER_SIDE_CURSORS: Trueand Django fetches in chunks client-side.response.streamingis True;response.streaming_contentyields chunks.response.contentraises an error.- Under ASGI, async iterators are supported, and Django warns when a sync iterator is used (it consumes it in a thread).
- Middleware:
GZipMiddlewareandConditionalGetMiddlewarecan buffer or skip streams.Content-Lengthis unknown, so clients show no progress bar. - Errors: if the query fails after the first chunk, the client receives a truncated file with status 200. Validate parameters first and consider a checksum or a final marker row.
- Long exports tie up a worker; for very large or slow exports, generate the file in a background task, store it (object storage), and send a download link.
FileResponseis the tool for serving existing files, with range support.
Add authorisation and row limits, and never include unescaped formulas (=, +, @) from user data in CSVs opened in spreadsheets (CSV injection).
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
ROOT_URLCONF=__name__,
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
import csv
from django.db import models, connection
from django.http import StreamingHttpResponse
from django.test import Client
from django.urls import path
class Student(models.Model):
roll_no = models.CharField(max_length=10)
name = models.CharField(max_length=40)
class Meta:
app_label = "school"
with connection.schema_editor() as editor:
editor.create_model(Student)
Student.objects.bulk_create([Student(roll_no=f"R{i:04d}", name=f"Student {i}") for i in range(1, 2501)], batch_size=500)
class Echo:
def write(self, value):
return value
def export(request):
writer = csv.writer(Echo())
def rows():
yield writer.writerow(["roll_no", "name"])
for row in Student.objects.values_list("roll_no", "name").order_by("id").iterator(chunk_size=1000):
yield writer.writerow(row)
response = StreamingHttpResponse(rows(), content_type="text/csv")
response["Content-Disposition"] = 'attachment; filename="students.csv"'
return response
urlpatterns = [path("export/", export)]
r = Client().get("/export/")
print(r.status_code, r.streaming, r["Content-Disposition"], "Content-Length" in r.headers)
chunks = list(r.streaming_content)
print(len(chunks), "chunks;", chunks[0], chunks[1], chunks[-1])
try:
r.content
except AttributeError as exc:
print("content:", exc)
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): 200 True attachment; filename="students.csv" False 2501 chunks; b'roll_no,name\r\n' b'R0001,Student 1\r\n' b'R2500,Student 2500\r\n' content: This StreamingHttpResponse instance has no `content` attribute. Use `streaming_content` instead.
Key points
- StreamingHttpResponse consumes an iterator and sends chunks as produced
- iterator(chunk_size) and values_list keep memory flat
- No Content-Length; errors after the first chunk cannot change the status
- Mind middleware, pgbouncer cursors and worker occupancy
- Offload very large exports to background jobs
Common mistakes
- Building the whole CSV in memory
- Iterating a normal QuerySet that caches every row
- Expecting a correct status code if the failure happens mid-stream
- Using server-side cursors behind transaction-pooling pgbouncer
- Writing user data into CSV without neutralising formulas
Follow-ups
- How does streaming behave under ASGI versus WSGI?
- How would you resume or retry a failed export?
- When is a background job better?
Tips
- Show the Echo buffer trick
- Mention iterator(chunk_size)
- State the trade-offs