def get_all_models(): import types, inspect from django.db.models import loading from django.db.models import Model apps = loading.get_apps() models = set() for app in apps: for attr in dir(app): v = getattr(app,attr) if inspect.isclass(v) and issubclass(v, Model): models.add(v) return list(models) def get_relations(all_models, the_model): """ """ from django.db.models.fields.related import OneToOneField, \ ManyToManyField, ForeignKey foreignkeys = [] one_to_one = [] many_to_many = [] for model in all_models: if not hasattr(model, '_meta'): print "skipping %s" % model continue for field in model._meta.fields: if isinstance(field, OneToOneField): # must come before FK to = field.rel.to if to not in all_models: raise ValueError if issubclass(to, the_model): one_to_one.append((model, to)) elif isinstance(field, ForeignKey): to = field.rel.to if to not in all_models: raise ValueError if issubclass(to, the_model): foreignkeys.append((model, to)) elif isinstance(field, ManyToManyField): to = field.rel.to if to not in all_models: raise ValueError if issubclass(to, the_model): many_to_many.append((model, to)) return foreignkeys, one_to_one, many_to_many