Version 3 (modified by Antonio Cavedoni <antonio@…>, 9 years ago) (diff)


Converting Django models into Graphviz DOT files

Inspired by this nice hack by Matt Biddulph I set out to create a similar thing for Django models. Below is an initial implementation, and here are some results generated with the OS X version of Graphviz:

I hope people might find it useful.

"""Django model to DOT (Graphviz) converter
by Antonio Cavedoni <>

Make sure your DJANGO_SETTINGS_MODULE is set to your project and call 
the script like this:

  $ python <appname>.<models module_name> > <filename>.dot


  $ python camera.models >

from django.db.models.base import ModelBase
from django.db.models.fields.related import \
    ForeignKey, OneToOneField, ManyToManyField

def generate_dot(model_module):
   print "digraph model {"

   for obj in dir(model_module):
      o = getattr(model_module, obj)
      if isinstance(o, ModelBase):
         for field in o._meta.fields:
            if type(field) in [ForeignKey, OneToOneField, ManyToManyField]:
               print '  %s -> %s_%s [label="%s"];' % \
                   (o.__name__, o.__name__,, type(field).__name__)
               print "  %s_%s -> %s" % \
               print "  %s -> %s_%s;" % (o.__name__, o.__name__,

   print "}"

if __name__ == "__main__":
   import sys
   _models = __import__(sys.argv[1])

Attachments (12)

Download all attachments as: .zip

Back to Top