Login

See what depends on a given model

Author:
jdunck
Posted:
February 7, 2011
Language:
Python
Version:
1.2
Tags:
model orm dependency
Score:
0 (after 2 ratings)

Riffing on http://djangosnippets.org/snippets/1024/ I didn't want a graph; I just wanted to see what depended on a specific model.

This does that nicely.

 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

More like this

  1. Log all interaction with user to the DB by inuwashi 4 years, 7 months ago
  2. Ajax auto-filtered Foreign Key Field by anentropic 5 years, 9 months ago
  3. Generic markup converter by ubernostrum 8 years, 5 months ago
  4. Choices helper by jacobian 6 years, 1 month ago
  5. Middleware to detect visitors who arrived from a search engine by exogen 8 years, 4 months ago

Comments

Please login first before commenting.