Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting items from a model to CSV Django / Python

I'm fairly new to django and Python and want to be able to export a list of items in my model i.e products. I'm looking at the documentation here - https://docs.djangoproject.com/en/dev/howto/outputting-csv/

I'm persuming I need will need to create a variable that stores all the data that I want. But not sure where it would within the snippet of code on the link above.

Apologies as this is a very noobish question but would really Any help at all.

Here is the code to my script so far:

import csv

from products.models import Product

from django.http import HttpResponse


def export_to_csv(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="mytest.csv"'
like image 466
Josh Davies Avatar asked Feb 22 '13 17:02

Josh Davies


1 Answers

Using django.db.models.query.QuerySet.values results in more optimised queries for my use case.

import csv
from datetime import datetime

from django.http import HttpResponse

# Populate this list with your model's fields
# Replace MODEL with your model
fields = [f.name for f in MODEL._meta.fields]

# The following code will live inside your view
timestamp = datetime.now().isoformat()

response = HttpResponse(content_type="text/csv")
response[
    "Content-Disposition"
] = f"attachment; filename={timestamp}.csv"
writer = csv.writer(response)

# Write the header row
writer.writerow(fields)

# Replace MODEL with your model
for row in MODEL.objects.values(*fields):
    writer.writerow([row[field] for field in fields])

return response
like image 59
robsco Avatar answered Nov 03 '22 08:11

robsco