Login

Streaming large CSV files via admin actions

Author:
asta-ko
Posted:
February 11, 2020
Language:
Python
Version:
Not specified
Tags:
admin csv admin-actions
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. Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 5 months, 1 week ago
  2. Crispy Form by sourabhsinha396 6 months ago
  3. ReadOnlySelect by mkoistinen 6 months, 1 week ago
  4. Verify events sent to your webhook endpoints by santos22 7 months, 1 week ago
  5. Django Language Middleware by agusmakmun 7 months, 3 weeks ago

Comments

Please login first before commenting.