DjangoGraphviz: modelviz_i18n.py

File modelviz_i18n.py, 5.9 KB (added by Nonexistent, 16 years ago)

Version with localized verbose_names instead of names

Line 
1#!/usr/bin/env python
2"""Django model to DOT (Graphviz) converter
3by Antonio Cavedoni <antonio@cavedoni.org>
4
5Make sure your DJANGO_SETTINGS_MODULE is set to your project or
6place this script in the same directory of the project and call
7the script like this:
8
9$ python modelviz.py [-h] [-d] <app_label> ... <app_label> > <filename>.dot
10$ dot <filename>.dot -Tpng -o <filename>.png
11
12options:
13 -h, --help
14 show this help message and exit.
15
16 -d, --disable_fields
17 don't show the class member fields.
18"""
19# -*- coding: utf-8 -*-
20__version__ = "0.8"
21__svnid__ = "$Id: modelviz.py 78 2007-07-15 19:04:47Z verbosus $"
22__license__ = "Python"
23__author__ = "Antonio Cavedoni <http://cavedoni.com/>"
24__contributors__ = [
25 "Stefano J. Attardi <http://attardi.org/>",
26 "limodou <http://www.donews.net/limodou/>",
27 "Carlo C8E Miron",
28 "Andre Campos <cahenan@gmail.com>",
29 "Justin Findlay <jfindlay@gmail.com>",
30 ]
31
32import getopt, sys
33
34from django.core.management import setup_environ
35from django.utils.translation import ugettext as _
36
37try:
38 import settings
39except ImportError:
40 pass
41else:
42 setup_environ(settings)
43
44from django.template import Template, Context
45from django.db import models
46from django.db.models import get_models
47from django.db.models.fields.related import \
48 ForeignKey, OneToOneField, ManyToManyField
49
50try:
51 from django.db.models.fields.generic import GenericRelation
52except ImportError:
53 from django.contrib.contenttypes.generic import GenericRelation
54
55head_template = """
56digraph name {
57 fontname = "Helvetica"
58 fontsize = 8
59
60 node [
61 fontname = "Helvetica"
62 fontsize = 8
63 shape = "plaintext"
64 ]
65 edge [
66 fontname = "Helvetica"
67 fontsize = 8
68 ]
69"""
70
71body_template = """
72 {% for model in models %}
73 {% for relation in model.relations %}
74 "{{ relation.target }}" [label=<
75 <TABLE BGCOLOR="palegoldenrod" BORDER="0" CELLBORDER="0" CELLSPACING="0">
76 <TR><TD COLSPAN="2" CELLPADDING="4" ALIGN="CENTER" BGCOLOR="olivedrab4"
77 ><FONT FACE="Helvetica Bold" COLOR="white"
78 >{{ relation.target }}</FONT></TD></TR>
79 </TABLE>
80 >]
81 "{{ model.name }}" -> "{{ relation.target }}"
82 [label="{{ relation.name }}"] {{ relation.arrows }};
83 {% endfor %}
84 {% endfor %}
85
86 {% for model in models %}
87 "{{ model.name }}" [label=<
88 <TABLE BGCOLOR="palegoldenrod" BORDER="0" CELLBORDER="0" CELLSPACING="0">
89 <TR><TD COLSPAN="2" CELLPADDING="4" ALIGN="CENTER" BGCOLOR="olivedrab4"
90 ><FONT FACE="Helvetica Bold" COLOR="white"
91 >{{ model.name }}</FONT></TD></TR>
92
93 {% if not disable_fields %}
94 {% for field in model.fields %}
95 <TR><TD ALIGN="LEFT" BORDER="0"
96 ><FONT {% if field.high %}COLOR="#7B7B7B" {% endif %}FACE="Helvetica Bold">{{ field.name }}</FONT
97 ></TD>
98 <TD ALIGN="LEFT"
99 ><FONT {% if field.high %}COLOR="#7B7B7B" {% endif %}FACE="Helvetica Bold">{{ field.type }}</FONT
100 ></TD></TR>
101 {% endfor %}
102 {% endif %}
103 </TABLE>
104 >]
105 {% endfor %}
106"""
107
108tail_template = """
109}
110"""
111
112def generate_dot(app_labels, **kwargs):
113 disable_fields = kwargs.get('disable_fields', False)
114
115 dot = unicode(head_template)
116
117 for app_label in app_labels:
118 app = models.get_app(app_label)
119 graph = Context({
120 'name': '"%s"' % app.__name__,
121 'disable_fields': disable_fields,
122 'models': []
123 })
124
125 for appmodel in get_models(app):
126 model = {
127 'name': appmodel._meta.verbose_name or appmodel.__name__,
128 'fields': [],
129 'relations': []
130 }
131
132 # model attributes
133 def add_attributes():
134 model['fields'].append({
135 'name': field.verbose_name or field.name,
136 'type': type(field).__name__,
137 'high': not field.editable or field.primary_key,
138 })
139
140 for field in appmodel._meta.fields:
141 add_attributes()
142
143 if appmodel._meta.many_to_many:
144 for field in appmodel._meta.many_to_many:
145 add_attributes()
146
147 # relations
148 def add_relation(extras=""):
149 _rel = {
150 'target': field.rel.to._meta.verbose_name or field.rel.to.__name__,
151 'type': type(field).__name__,
152 'name': field.verbose_name or field.name,
153 'arrows': extras
154 }
155 if _rel not in model['relations']:
156 model['relations'].append(_rel)
157
158 for field in appmodel._meta.fields:
159 if isinstance(field, ForeignKey):
160 add_relation()
161 elif isinstance(field, OneToOneField):
162 add_relation("[arrowhead=none arrowtail=none]")
163
164 if appmodel._meta.many_to_many:
165 for field in appmodel._meta.many_to_many:
166 if isinstance(field, ManyToManyField):
167 add_relation("[arrowhead=normal arrowtail=normal]")
168 elif isinstance(field, GenericRelation):
169 add_relation(
170 '[style="dotted"] [arrowhead=normal arrowtail=normal]')
171 graph['models'].append(model)
172
173 t = Template(body_template)
174 dot += '\n' + t.render(graph)
175
176 dot += '\n' + tail_template
177
178 return dot
179
180def main():
181 try:
182 opts, args = getopt.getopt(sys.argv[1:], "hd",
183 ["help", "disable_fields"])
184 except getopt.GetoptError, error:
185 print __doc__
186 sys.exit(error)
187 else:
188 if not args:
189 print __doc__
190 sys.exit()
191
192 kwargs = {}
193 for opt, arg in opts:
194 if opt in ("-h", "--help"):
195 print __doc__
196 sys.exit()
197 if opt in ("-d", "--disable_fields"):
198 kwargs['disable_fields'] = True
199 print generate_dot(args, **kwargs).encode('utf-8')
200
201if __name__ == "__main__":
202 main()
Back to Top