Skip to content

Instantly share code, notes, and snippets.

@miraculixx
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miraculixx/05e1347b50a75467559c to your computer and use it in GitHub Desktop.
Save miraculixx/05e1347b50a75467559c to your computer and use it in GitHub Desktop.
Django Queryset CSV Exporter
class CSVExport(object):
"""
A generic CSV exporter for any queryset. Use with a
file object or the default storage class.
Use with a file object:
queryset = SomeModel.objects.all()
exporter = CSVExport(queryset)
export.export(file)
Use with the default storage class, give a location and filename
queryset = SomeModel.objects.all()
exporter = CSVExport(queryset)
export.export_to_filepath(location, 'somefile.csv')
Specify the fields in the constructor:
exporter = CSVExport(queryset, fields)
where fields is a list of field names. If not given,
defaults to the field names of the first object in the queryset.
"""
def __init__(self, queryset, fields=None):
self.queryset = queryset
self.fields = None
def export_to_filepath(self, location, filename):
"""
export to a file as given in the path. will
create a file using Django's storage class,
and call export() on it
"""
storage_class = get_storage_class()
file = storage_class(location=location)
with open(file.path(filename), 'wb') as f:
self.export(f)
def export(self, fileobj, header=True):
"""
export the queryset into file.
:param file: the file object to use
:return: the csv.writer instance
"""
# create a CSV writer
writer = csv.writer(fileobj)
# get fields
fields = self.fields
if not fields:
first = self.queryset[0]
fields = [f.name for f in first._meta.fields]
# write header
if header:
writer.writerow(fields)
# write data
for obj in self.queryset:
writer.writerow([getattr(obj, f) for f in fields])
return writer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment