Export QuerySet to CSV

Posted: March 31st, 2010 | Author: Davo | Filed under: Django | Tags: | 1 Comment »

Converting a queryset to CSV:

# available from python 2.3+
import csv 

def export_to_csv(request):
    # get the response object, this can be used as a stream.
    response = HttpResponse(mimetype='text/csv')
    # force download.
    response['Content-Disposition'] = 'attachment;filename="export.csv"'

    # the csv writer
    writer = csv.writer(response)

    # just any model...
    cars = Car.objects.filter()        

    for car in cars:
        writer.writerow([car.model, car.year])

    return response

One Comment on “Export QuerySet to CSV”

  1. 1 Tweets that mention Export QuerySet to CSV | Django foo -- Topsy.com said at 9:34 pm on April 2nd, 2010:

    [...] This post was mentioned on Twitter by Django Ireland. Django Ireland said: Export QuerySet to CSV | Django foo http://bit.ly/cjhTxy [...]


Leave a Reply