Skip to content

Instantly share code, notes, and snippets.

Created August 13, 2015 18:33
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Dump querysets to csv
# Via:
import csv
from django.db.models.loading import get_model
def dump2csv(qs, outfile_path):
Takes in a Django queryset and spits out a CSV file.
>> from dump2csv import dump2csv
>> from dummy_app.models import *
>> qs = DummyModel.objects.all()
>> dump2csv.dump(qs, './data/dump.csv')
Based on a snippet by zbyte64::
model = qs.model
writer = csv.writer(open(outfile_path, 'w'))
headers = []
for field in model._meta.fields:
for obj in qs:
row = []
for field in headers:
val = getattr(obj, field)
if callable(val):
val = val()
if type(val) == unicode:
val = val.encode("utf-8")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment