blob: 4353793a5dd7b5c082854c09b0c591c4c93589e1 [file] [log] [blame]
Sapan Bhatiad7425452013-09-03 11:45:15 -04001#!/usr/bin/python
2
3import os
4import pdb
5import sys
6import json
7
8sys.path.append('.')
9
10os.environ.setdefault("DJANGO_SETTINGS_MODULE", "planetstack.settings")
11
12from django.db.models.fields.related import ForeignKey
Sapan Bhatiad7425452013-09-03 11:45:15 -040013
Scott Bakerceb464b2014-04-03 11:03:11 -070014# defaults
15app = "core"
16output = "-json"
Sapan Bhatiad7425452013-09-03 11:45:15 -040017
Scott Bakerceb464b2014-04-03 11:03:11 -070018# syntax: dmdot [-json | -dot] [app_name]
19
20# poor man's argument parser
21for arg in sys.argv[1:]:
22 if arg.startswith("-"):
23 output = arg
24 else:
25 app = arg
26
27app = app + ".models"
28#models_module = imp.load_source(app, ".")
29models_module = __import__(app)
30for part in app.split(".")[1:]:
31 models_module = getattr(models_module,part)
32
33PlCoreBase = getattr(models_module,"PlCoreBase")
34
Sapan Bhatiad7425452013-09-03 11:45:15 -040035model_classes = []
36class_names = []
Scott Bakerceb464b2014-04-03 11:03:11 -070037lower_class_names = {}
38for classname in dir(models_module):
39 c = getattr(models_module, classname, None)
Sapan Bhatiad7425452013-09-03 11:45:15 -040040 if type(c)==type(PlCoreBase):
41 model_classes.append(c)
42 class_names.append(c.__name__)
Scott Bakerceb464b2014-04-03 11:03:11 -070043 lower_class_names[c.__name__.lower()] = c
Sapan Bhatiad7425452013-09-03 11:45:15 -040044
Scott Bakerceb464b2014-04-03 11:03:11 -070045# django doesn't use the correct case in field.name.title() for objects that
46# have CamelCased class names. So, compare everything in lower case.
Sapan Bhatiad7425452013-09-03 11:45:15 -040047
48if (output=='-dot'):
49 print "digraph plstack {";
50 for c in model_classes:
51 fields = c._meta.fields
52 for f in fields:
Scott Bakerceb464b2014-04-03 11:03:11 -070053 if type(f)==ForeignKey and f.name.lower() in lower_class_names:
54 linked_class = lower_class_names[f.name.lower()]
55 print '\t"%s"->"%s";'%(c.__name__,linked_class.__name__)
Sapan Bhatiad7425452013-09-03 11:45:15 -040056 print "}\n";
57elif (output=='-json'):
58 d = {}
59 for c in model_classes:
60 fields = c._meta.fields
61 for f in fields:
Scott Bakerceb464b2014-04-03 11:03:11 -070062 if type(f)==ForeignKey and f.name.lower() in lower_class_names:
63 linked_class = lower_class_names[f.name.lower()]
Sapan Bhatiad7425452013-09-03 11:45:15 -040064 try:
Scott Bakerceb464b2014-04-03 11:03:11 -070065 d[c.__name__].append(linked_class.__name__)
Sapan Bhatiad7425452013-09-03 11:45:15 -040066 except KeyError:
Scott Bakerceb464b2014-04-03 11:03:11 -070067 d[c.__name__]=[linked_class.__name__]
Sapan Bhatiad7425452013-09-03 11:45:15 -040068 print json.dumps(d,indent=4)
Scott Bakerceb464b2014-04-03 11:03:11 -070069
70