简体   繁体   中英

Export CSV files in a bulk in Django

I'm creating a custom administration action to download a list of orders as a CSV file. I've this in my orders/admin.py:


def export_to_csv(modeladmin, request, queryset):
    opts = modeladmin.model._meta   # opts = options
    for order in queryset:
        content_disposition = f'attachment; filename=OrderID-{order.id}.csv'
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = content_disposition
    writer = csv.writer(response)

    fields = [field for field in opts.get_fields() if not field.many_to_many
              and not field.one_to_many]
    writer.writerow([field.verbose_name for field in fields])
    # Write data rows
    for obj in queryset:
        data_row = []
        for field in fields:
            value = getattr(obj, field.name)
            if isinstance(value, datetime.datetime):
                value = value.strftime('%d/%m/%Y')
            data_row.append(value)
        writer.writerow(data_row)
    return response

However, this code doesn't download more than one csv file Even when I've selected more than one.

You cannot download several files via 1 HTTP request, details .

So, you can zip your csvs in one zip file and return it like this answer describes .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM