Created
January 11, 2016 14:54
-
-
Save Visgean/12989a2d6c2a960f97de to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import csv | |
from optparse import make_option | |
from django.conf import settings | |
from django.core.management.base import BaseCommand, CommandError | |
from django.utils import translation | |
class Command(BaseCommand): | |
help = 'Export any model to CSV' | |
option_list = BaseCommand.option_list + ( | |
make_option( | |
"-f", | |
"--file", | |
dest="filename", | |
help="specify export file", | |
metavar="FILE" | |
), | |
make_option( | |
"-m", | |
"--model", | |
dest="model", | |
help="example: order.OrderLog", | |
metavar="model" | |
), | |
) | |
def handle(self, *args, **options): | |
translation.activate(settings.LANGUAGE_CODE) | |
filename = options.get('filename', None) | |
if filename is None: | |
raise CommandError("Option `--file=...` must be specified.") | |
model_path = options.get('model', None) | |
if model_path is None: | |
raise CommandError("Option `--model=...` must be specified.") | |
app_label, model_label = model_path.split('.') | |
try: # django before 1.7 | |
from django.db.models.loading import get_model | |
model = get_model(app_label, model_label) | |
except ImportError: # new django | |
from django.apps import apps | |
model = apps.get_model(app_label=app_label, model_name=model_label) | |
with open(filename, 'w') as csv_file: | |
export_fields = model._meta.get_all_field_names() | |
writer = csv.DictWriter(csv_file, export_fields) | |
writer.writeheader() | |
writer.writerows( | |
[ | |
{ | |
field: log.__getattribute__(field) | |
for field in export_fields | |
} for log in model.objects.all() | |
] | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment