Skip to content

Instantly share code, notes, and snippets.

@carymrobbins
Created November 25, 2014 15:16
Show Gist options
  • Save carymrobbins/70920a82671b601512f4 to your computer and use it in GitHub Desktop.
Save carymrobbins/70920a82671b601512f4 to your computer and use it in GitHub Desktop.
Find all model classes that reference another via a foreign key.
from django.db.models import get_models
def fk_refs(klass):
"""Find all model classes that reference another via a foreign key.
:type Model
:rtype dict[Model, list[Field]]
"""
result = {}
for m in get_models():
for f in m._meta.fields:
if f.rel and f.rel.to == klass:
result.setdefault(m, []).append(f)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment