Login

Streaming large CSV files via admin actions

Author:
asta-ko
Posted:
February 11, 2020
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

Based on https://djangosnippets.org/snippets/2020/ and https://stackoverflow.com/questions/5146539/streaming-a-csv-file-in-django Can be used on really large querysets.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import csv
from io import StringIO
from django.contrib import admin
from django.core.paginator import Paginator
from django.http import StreamingHttpResponse

def export_as_csv_action(description="Export selected objects as CSV file", header=True):
    def export_as_csv(modeladmin, request, queryset):

        def chunked_iterator(queryset, chunk_size=1000):
            paginator = Paginator(queryset, chunk_size)
            for page in range(1, paginator.num_pages + 1):
                for obj in paginator.page(page).object_list:
                    yield obj

        queryset = chunked_iterator(queryset)

        def row_generator(queryset):

            csvfile = StringIO()
            csvwriter = csv.writer(csvfile)

            def read_and_flush():
                csvfile.seek(0)
                data = csvfile.read()
                csvfile.seek(0)
                csvfile.truncate()
                return data

            header = False

            if not header:
                header = True
                csvwriter.writerow(['email','last_name'])
                data = read_and_flush()
                yield data

            for obj in queryset:
                csvwriter.writerow([obj.email, obj.last_name]) #your data here

                data = read_and_flush()
                yield data

        response = StreamingHttpResponse(row_generator(queryset),
                                         content_type="text/csv")
        response['Content-Disposition'] = 'attachment; filename=%s.csv' % 'yourfilename'

        return response

    export_as_csv.short_description = description
    return export_as_csv

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 9 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.