Exporting items from a model to CSV Django / Python

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

Depending on the scenario - you may want to have a CSV of your model. If you have access to the Django Admin site, you can plug in a generic action for any model displayed as a list (google: django admin actions)

http://djangosnippets.org/snippets/790/

If you're operating with a console (python manage.py ...), you can use such a script, which I just used:

(place it in: yourapp/management/commands/model2csv.py)

"""
 Prints CSV of all fields of a model.
"""

from django.core.management.base import BaseCommand, CommandError
import csv
import sys

class Command(BaseCommand):
    help = ("Output the specified model as CSV")
    args = '[appname.ModelName]'

    def handle(self, *app_labels, **options):
        from django.db.models import get_model
        app_name, model_name = app_labels[0].split('.')
        model = get_model(app_name, model_name)
        field_names = [f.name for f in model._meta.fields]
        writer = csv.writer(sys.stdout, quoting=csv.QUOTE_ALL)
        writer.writerow(field_names)
        for instance in model.objects.all():
            writer.writerow([unicode(getattr(instance, f)).encode('utf-8') for f in field_names])

This does not catch any exceptions etc., but as an Admin you won't cause them to be raised, right?

Use it like:

./manage.py model2csv my_ecommerce.Product > products.csv

You can also make a template to assist in formatting!

The template is a common Django template

from django.template import loader
def export_to_csv(request):
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename="products-list.csv"'
    template = loader.get_template('templates/products_template.csb')
    response.write(template.render(Context({'products': Products.objects.all()})))
    return response

Have a look at the python csv module.

You'll probably want to get the models fields with

def get_model_fields(model):
    return model._meta.fields

Then use

getattr(instance, field.name)

to get the field values (as in this question).

Then you'll want something like

with open('your.csv', 'wb') as csvfile:
    writer = csv.writer(csvfile)
    # write your header first
    for obj in YourModel.objects.all():
        row = ""
        for field in fields:
             row += getattr(obj, field.name) + ","
        writer.writerow(row)

It's a bit verbose (and untested), but it should give you an idea. (Oh and don't forget to close your file)