Login

Automatic graph of your database structure

Author:
adamlofts
Posted:
November 6, 2008
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

This script generates an GraphViz graph of your database structure from your django models.

See the usage if the file underneath the license.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/env python

# Copyright (C) 2008 Adam Lofts
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# This program generates a graphviz file to plot a graph of your database layout.
# 
# Usage:
#
# Set PYTHONPATH and DJANGO_SETTINGS_MODULE for your django app
# ./graph.py <django_app_name> | dot -Tpng -o graph.png

import sys
from django.db.models import get_app, get_models

def graph(app, outfile):

    models = get_models(get_app(app))

    outfile.write("digraph G {\n")

    for model in models:

        # Format the shape
        name = model._meta.object_name
        label = "%s\\n" % name + "\\n".join([field.name for field in model._meta._fields()])
        outfile.write("%s [shape=box,label=\"%s\"];" % (name, label))

        # Draw the relations
        for related in model._meta.get_all_related_objects():
            outfile.write("\t%s -> %s;\n" % (name, related.model._meta.object_name))

        for related in model._meta.get_all_related_many_to_many_objects():
            outfile.write("\t%s -> %s [dir=both];\n" % (name, related.model._meta.object_name))

    outfile.write("}\n")

if __name__=="__main__":

    if len(sys.argv) != 2:
        print "graph.py <appname>"
        print "\tWrites a graph of your models suitable for processing with graphviz"
        sys.exit(1)

    graph(sys.argv[1], sys.stdout)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.