Last active
November 9, 2017 18:11
-
-
Save baxeico/1a06f5491f175510356359421b22cdec to your computer and use it in GitHub Desktop.
Django custom command to write model fields on an Excel file (e.g. for documentation purposes)
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 | |
from __future__ import unicode_literals | |
import logging | |
from django.core.management.base import BaseCommand, CommandError | |
from django.apps import apps | |
from xlsxwriter.workbook import Workbook | |
logger = logging.getLogger(__name__) | |
class Command(BaseCommand): | |
help = 'Export all models of a given app to Excel file' | |
def add_arguments(self, parser): | |
parser.add_argument('app_labels', nargs='+', type=str) | |
parser.add_argument('output', type=str) | |
parser.add_argument('--exclude-models', dest="exclude_models_file", | |
type=file) | |
parser.add_argument('--include-reverse-relations', action='store_true', | |
dest="include_reverse_relations", default=False) | |
def handle(self, *args, **options): | |
workbook = Workbook(options['output'], {'constant_memory': True}) | |
bold = workbook.add_format({'bold': True}) | |
headers = ['Field', 'Type'] | |
exclude_models = [] | |
if options['exclude_models_file']: | |
exclude_models = options['exclude_models_file'].read().splitlines() | |
for app_label in options['app_labels']: | |
app_config = apps.get_app_config(app_label) | |
app_models = app_config.get_models(include_auto_created=False) | |
for model in app_models: | |
model_name = model.__name__ | |
if model_name in exclude_models: | |
continue | |
worksheet_name = '%s - %s' % (app_label, model_name) | |
if len(worksheet_name) > 31: | |
worksheet_name = '%s - %s' % (app_label[:3], model_name) | |
worksheet = workbook.add_worksheet(worksheet_name) | |
worksheet.write_row(0, 0, headers, bold) | |
worksheet.set_column(0, len(headers), 30) | |
fields = model._meta.get_fields() | |
row = 1 | |
for f in fields: | |
try: | |
fieldname = f.verbose_name | |
except: | |
fieldname = f.name | |
fieldtype = f.__class__.__name__ | |
if (options['include_reverse_relations'] or | |
fieldtype not in ('ManyToOneRel', 'ManyToManyRel', | |
'OneToOneRel')): | |
worksheet.write(row, 0, fieldname.strip()) | |
worksheet.write(row, 1, fieldtype) | |
row += 1 | |
workbook.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment