CSV Export from QuerySet

A snippet showing how to export data to CSV from a view.


# models.py
from django.db import models
class Order(models.Model):
    number = models.CharField(max_length=20)
    total = models.DecimalField(max_digits=8, decimal_places=2)
  

# admin.py
from django.contrib import admin
from .models import Order
@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
    list_display = ("number","total")
  

# Result (view)

from django.http import HttpResponse
import csv
def export_orders_csv(request):
    response = HttpResponse(content_type="text/csv")
    response["Content-Disposition"] = 'attachment; filename="orders.csv"'
    writer = csv.writer(response)
    writer.writerow(["number", "total"])
    for o in Order.objects.all().only("number","total"):
        writer.writerow([o.number, o.total])
    return response
  
Explanation:
  • Set correct content type and Content-Disposition header.
  • Iterate efficiently with .only() to reduce memory.
Previous snippet
UUID Primary Keys
Next snippet
CSV Import to Models
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.