Login

See what depends on a given model

Author:
jdunck
Posted:
February 7, 2011
Language:
Python
Version:
1.2
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. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 8 months ago

Comments

Please login first before commenting.