Skip to content

Instantly share code, notes, and snippets.

@RasPhilCo
Created September 1, 2015 02:47
Show Gist options
  • Save RasPhilCo/af23f912fc92d5e38a66 to your computer and use it in GitHub Desktop.
Save RasPhilCo/af23f912fc92d5e38a66 to your computer and use it in GitHub Desktop.
Export django model to csv
import csv
import collections
from operator import attrgetter
from myApp.models import User
csvfile = open("users.csv", "wb")
objects = User.objects.all()
fields = collections.OrderedDict([("First name", "first_name"),("Last name", "last_name"),("Email", "email"),])
writer = csv.writer(csvfile, quoting=csv.QUOTE_ALL)
row_headers = fields.keys()
writer.writerow(row_headers)
for obj in objects:
row = [attrgetter(fields[header])(obj) for header in row_headers]
for count, column in enumerate(row):
if callable(column):
row[count] = column()
else:
pass
if type(column) is unicode:
row[count] = column.encode('utf8')
else:
pass
writer.writerow(row)
# check that all objects were added to csv
# wc users.csv (minus 1, the header) should be equivalent to User.objects.count()
# secure copy users.csv out of box
# scp [email protected]:/path/to/users.csv ./local/path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment