1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49 | 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
|
Comments