Version 3 (modified by Antonio Cavedoni <antonio@…>, 18 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 <antonio@cavedoni.org>

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

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

Example:

  $ python modelviz.py camera.models > foo.dot
"""

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__, field.name, type(field).__name__)
               print "  %s_%s -> %s" % \
                   (o.__name__, field.name, field.rel.to.__name__)
            else:
               print "  %s -> %s_%s;" % (o.__name__, o.__name__, field.name)

   print "}"

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

Attachments (12)

Download all attachments as: .zip

Note: See TracWiki for help on using the wiki.
Back to Top