Skip to main content

Simple CSV export for Django

Project description

Easy Django CSV

Memory-efficient CSV export library for Django with support for both traditional and streaming exports.

Installation

pip install easy-django-csv

Quick Start

Basic CSV Export

The simplest way to export data with manual row management:

from easy_django_csv import CSVExporter

def export_users(request):
    exporter = CSVExporter(
        headers=['ID', 'Name', 'Email'],
        filename='users_export'
    )
    
    for user in User.objects.all():
        exporter.add_row([user.id, user.name, user.email])
    
    return exporter.export()

Model CSV Export

Automatically export a Django model with custom serializer:

from easy_django_csv import ModelCSVExport

def export_users(request):
    def user_serializer(user):
        return [user.id, user.name, user.email, user.date_joined]
    
    exporter = ModelCSVExport(
        headers=['ID', 'Name', 'Email', 'Joined'],
        filename='users',
        serializer=user_serializer,
        queryset=User.objects.all()
    )
    
    return exporter.export()

Auto-Generated Headers

Let the exporter generate headers from model fields:

from easy_django_csv import ModelCSVExport

def export_users(request):
    exporter = ModelCSVExport(
        filename='users',
        serializer=lambda u: [u.id, u.name, u.email],
        queryset=User.objects.all()
        # headers will be auto-generated from model fields
    )
    
    return exporter.export()

Streaming Export (Large Datasets)

For datasets with thousands of rows, use streaming to reduce memory usage:

from easy_django_csv import StreamingModelCSVExport

def export_users(request):
    exporter = StreamingModelCSVExport(
        headers=['ID', 'Name', 'Email'],
        filename='users_large',
        serializer=lambda u: [u.id, u.name, u.email],
        iterator=User.objects.all().iterator(chunk_size=1000)
    )
    
    return exporter.export()

Auto Export Model (Convenience Function)

Export all fields from a model automatically:

from easy_django_csv import export_model

def export_users(request):
    return export_model(User.objects.all())

API Reference

CSVExporter

Traditional CSV exporter with manual row management.

Parameters:

  • headers (List[str]): Column headers
  • filename (str): Output filename without .csv extension (default: "export")
  • validation (bool): Validate row lengths match headers (default: True)

Methods:

  • add_row(row: List): Add a single row
  • add_rows(rows: List[List]): Add multiple rows
  • export(): Returns HttpResponse

Example:

exporter = CSVExporter(headers=['Name', 'Age'])
exporter.add_row(['Alice', 30])
exporter.add_row(['Bob', 25])
return exporter.export()

ModelCSVExport

Export Django querysets with automatic iteration.

Parameters:

  • headers (List[str], optional): Column headers (auto-generated if None)
  • filename (str): Output filename (default: "export")
  • serializer (callable): Function to convert model instance to list
  • queryset (QuerySet): Django queryset to export
  • hide_headers (bool): Skip writing headers (default: False)

Example:

exporter = ModelCSVExport(
    headers=['ID', 'Email'],
    filename='newsletter',
    serializer=lambda n: [n.id, n.email],
    queryset=Newsletter.objects.filter(active=True)
)
return exporter.export()

StreamingModelCSVExport

Memory-efficient streaming export for large datasets.

Parameters:

  • headers (List[str], optional): Column headers
  • filename (str): Output filename (default: "export")
  • serializer (callable): Function to convert model instance to list
  • iterator (iterator): Django queryset with .iterator() called

Example:

exporter = StreamingModelCSVExport(
    headers=['ID', 'Name', 'Email'],
    serializer=lambda u: [u.id, u.name, u.email],
    iterator=User.objects.all().iterator(chunk_size=2000)
)
return exporter.export()

export_model()

Convenience function to export all model fields automatically.

Parameters:

  • queryset (QuerySet): Django queryset to export

Returns: HttpResponse with CSV data

Example:

return export_model(User.objects.filter(is_active=True))

Advanced Examples

Custom Serializer with Formatting

from datetime import datetime

def user_serializer(user):
    return [
        user.id,
        user.get_full_name(),
        user.email,
        'Active' if user.is_active else 'Inactive',
        user.date_joined.strftime('%Y-%m-%d')
    ]

exporter = ModelCSVExport(
    headers=['ID', 'Full Name', 'Email', 'Status', 'Joined'],
    serializer=user_serializer,
    queryset=User.objects.all()
)

Filtered Export

from django.utils import timezone
from datetime import timedelta

# Export users who joined in the last 30 days
last_month = timezone.now() - timedelta(days=30)
recent_users = User.objects.filter(date_joined__gte=last_month)

exporter = ModelCSVExport(
    filename='recent_users',
    serializer=lambda u: [u.id, u.email, u.date_joined],
    queryset=recent_users
)
return exporter.export()

Export with Related Fields

def order_serializer(order):
    return [
        order.id,
        order.customer.name,  # ForeignKey
        order.customer.email,
        order.total,
        order.created_at.strftime('%Y-%m-%d')
    ]

# Use select_related for performance
queryset = Order.objects.select_related('customer').all()

exporter = ModelCSVExport(
    headers=['Order ID', 'Customer', 'Email', 'Total', 'Date'],
    serializer=order_serializer,
    queryset=queryset
)

Method Chaining with CSVExporter

def export_products(request):
    return (
        CSVExporter(headers=['ID', 'Name', 'Price'])
        .add_row([1, 'Product A', 19.99])
        .add_row([2, 'Product B', 29.99])
        .add_row([3, 'Product C', 39.99])
        .export()
    )

Performance Tips

  1. Use streaming for large datasets (more than 10,000 rows)
  2. Always use .iterator() with StreamingModelCSVExport
  3. Use .select_related() and .prefetch_related() to avoid N+1 queries
  4. Set appropriate chunk_size in iterator (1000-2000 is usually good)
# Good: Efficient for large datasets
queryset = User.objects.select_related('profile').iterator(chunk_size=1000)
exporter = StreamingModelCSVExport(
    serializer=lambda u: [u.id, u.profile.bio],
    iterator=queryset
)

# Bad: Loads everything into memory
queryset = User.objects.all()  # Don't pass this to StreamingModelCSVExport

When to Use Each Exporter

Exporter Use Case Dataset Size
CSVExporter Manual row control, simple exports Small (< 1000 rows)
ModelCSVExport Standard Django model exports Small to Medium (< 10,000 rows)
StreamingModelCSVExport Large exports, memory efficient Large (> 10,000 rows)
export_model() Quick exports with all fields Any size

Requirements

  • Python >= 3.8
  • Django >= 3.2

License

MIT License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

easy_django_csv-0.1.3.tar.gz (4.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

easy_django_csv-0.1.3-py3-none-any.whl (5.3 kB view details)

Uploaded Python 3

File details

Details for the file easy_django_csv-0.1.3.tar.gz.

File metadata

  • Download URL: easy_django_csv-0.1.3.tar.gz
  • Upload date:
  • Size: 4.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.8

File hashes

Hashes for easy_django_csv-0.1.3.tar.gz
Algorithm Hash digest
SHA256 1e8c9293472aba87e9ebaeaedb4b71391722eeb8c333d7c6730e89c43dfa83b2
MD5 1f208ecf38441b82f8e4dceea2304cb5
BLAKE2b-256 4ea781ecb894902980e7229045f9ba5536e6c38433006303fa39a01c4c1f0ce4

See more details on using hashes here.

File details

Details for the file easy_django_csv-0.1.3-py3-none-any.whl.

File metadata

File hashes

Hashes for easy_django_csv-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 f9def79e5850b6a59ad7fda3558fb9d8f9cb744d47242e776bde2aad46fe18bb
MD5 79609e6af6d207ef54d0ee3bb916f943
BLAKE2b-256 06accdbabee8250cf8d5088ad881b2f74b40ff30a34147da331014d8a2319d11

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page