Skip to content

Instantly share code, notes, and snippets.



Last active Nov 9, 2017
What would you like to do?
Django custom command to write model fields on an Excel file (e.g. for documentation purposes)
# coding=utf-8
from __future__ import unicode_literals
import logging
from 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",
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:
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:
fieldname = f.verbose_name
fieldname =
fieldtype = f.__class__.__name__
if (options['include_reverse_relations'] or
fieldtype not in ('ManyToOneRel', 'ManyToManyRel',
worksheet.write(row, 0, fieldname.strip())
worksheet.write(row, 1, fieldtype)
row += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.