Created
November 18, 2023 22:54
-
-
Save deedy5/88924287f6b713ad30ca2cf456932a19 to your computer and use it in GitHub Desktop.
Django admin export - very fast csv streaming
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
from django.contrib import admin | |
from django.http import StreamingHttpResponse | |
import csv | |
class ExampleModel(models.Model): | |
field1 = models.CharField(max_length=100) | |
field2 = models.CharField(max_length=100) | |
field3 = models.EmailField(max_length=100) | |
# ... other fields ... | |
class ExampleAdmin(admin.ModelAdmin): | |
list_display = ["field1", "field2", "field3"] | |
actions = ["export_data"] | |
def export_data(self, request, queryset): | |
class Echo: | |
def write(self, value): | |
return value | |
def generate_csv_stream(): | |
echo = Echo() | |
writer = csv.writer(echo) | |
# Write headers | |
headers = self.list_display | |
yield writer.writerow(headers) | |
# Stream the rows | |
for obj in queryset.iterator(): | |
row = [str(getattr(obj, field, "")) for field in self.list_display] | |
yield writer.writerow(row) | |
streaming_content = generate_csv_stream() | |
content_type = "text/csv" | |
response = StreamingHttpResponse(streaming_content, content_type=content_type) | |
response["Content-Disposition"] = 'attachment; filename="export_data.csv"' | |
return response | |
export_data.short_description = "Export selected data as CSV" | |
admin.site.register(ExampleModel, ExampleAdmin) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment