~luisbg/djangodb2graph/trunk

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
54
55
56
57
58
59
60
61
62
63
64
# Script to convert the models.py database schema to a dot file
# that graphviz will convert to a png graph.

# USAGE: after running this script run the command:
# $> dot -Tpng graph.dot -o graph.png

# The script runs twice through the models.py file.
# 1st iteration: Grab the classes and fields and translate to dot format
# 2nd iteration: Grab the links between tables and translate to dot format

# Any questions about the script or requests, please contact:
# Luis de Bethencourt <luis.debethencourt@sun.com>

import string

models = open("models.py", "r")
graph = open("graph.dot", "w")
graph.write('digraph structs {\n')
graph.write('    node [shape=record];\n')
new_line = ''

for line in models.readlines():
    if line.find('models.Model') != -1:
        if new_line != '':
            new_line = new_line + '"];\n'
#            print new_line
            graph.write(new_line + '\n')
        new_class = line.split()[1].split('(')[0]
        new_line = '    ' + new_class + ' [label="<0> ' + new_class
        c = 1

    if line.find('Field') != -1:
        new_line = new_line + ' | ' + line.split()[0]

    if line.find('ForeignKey') != -1:
        new_line = new_line + ' | <' + str(c) + '> ' + line.split()[0]
        c += 1

graph.write(new_line + '"];' + '\n')

graph.write('\n')
models.close()
models = open("models.py", "r")

for line in models.readlines():
    if line.find('models.Model') != -1:
        new_class = line.split()[1].split('(')[0]
        c = 1
    if line.find('ForeignKey') != -1:
        key = line.split()[2].split('(')[1][:-1]
        if key == "'self'":
           new_line = new_class + ':' + str(c) + '-> ' + new_class + ':0'
        else:
           new_line = new_class + ':' + str(c) + ' -> ' + key + ':0'
        print new_line
        graph.write('    ' + new_line + '\n')
        c += 1

graph.write('\n')
graph.write('    rankdir=LR\n')
graph.write('}')

models.close()
graph.close()