Skip to content

Instantly share code, notes, and snippets.

@jackdied
Created July 9, 2013 20:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackdied/5960871 to your computer and use it in GitHub Desktop.
Save jackdied/5960871 to your computer and use it in GitHub Desktop.
import django.db
import collections
all_models = django.db.models.get_models()
def find_deps(models):
""" return a dict of {model : [all dependent models] """
deps = collections.defaultdict(set)
name_to_model = {}
for model in models:
table = model._meta.db_table
name_to_model[table] = model
others = model._meta.get_all_related_objects()
for other in others:
oth_table = other.model._meta.db_table
name_to_model[oth_table] = other.model
deps[table].add(oth_table)
old_count = 0
new_count = sum(len(l) for l in deps.values())
while old_count != new_count:
old_count = new_count
for tab, others in deps.items():
new_others = set(others)
for item in others:
new_others |= deps[item]
deps[tab] = new_others
new_count = sum(len(l) for l in deps.values())
out = {}
for k, v in deps.items():
out[name_to_model[k]] = map(name_to_model.__getitem__, v)
return out
def dependency_names():
model_to_deps = find_deps(all_models)
text_deps = {}
for k, v in model_to_deps.items():
text_deps[k._meta.db_table] = [m._meta.db_table for m in v]
return text_deps
def print_deps(deps):
print 'table => list of tables in the cascade'
print '-' * 80
for tab, others in sorted(deps.items()):
if others:
print '%s => %s' % (tab, ', '.join(sorted(list(others))))
if __name__ == '__main__':
print_deps(dependency_names())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment