tags:

views:

58

answers:

3

I use django, and have a lengthy models.py file.

class Foo(models.Model):
     name = models.CharField()

class Bar(models.Model):
     name = models.CharField()

class Fab(models.Model):
     name = models.CharField()

Is there a way to make a list of all the classes in the file which are an instance of (models.Model)?

+2  A: 

When you say:

... classes in the file which are an instance of ...

i think you mean "...classes in the file which are subclass of...". If so:

classes = [cls for cls in dir(module)
           if issubbclass(getattr(module, cls), models.Model)]
mg
@Max Shawabkeh: thanks for the correction. I was thinking about `__dict__` and `values` and i did that stupid error.
mg
A: 

The inspect module might help you. Here's some code from a plugin manager class I wrote that might serve as an example.

def load_plugin_file(self, pathname):
    '''Return plugin classes in a plugin file.'''

    name, ext = os.path.splitext(os.path.basename(pathname))
    f = file(pathname, 'r')
    module = imp.load_module(name, f, pathname, 
                             ('.py', 'r', imp.PY_SOURCE))
    f.close()

    plugins = []
    for dummy, member in inspect.getmembers(module, inspect.isclass):
        if issubclass(member, Plugin):
            p = member(*self.plugin_arguments,
                       **self.plugin_keyword_arguments)
            if self.compatible_version(p.required_application_version):
                plugins.append(p)

    return plugins

The other way to do it might be to use the builtin functions globals, issubclass, and isinstance.

Lars Wirzenius
+4  A: 

Django provides some utility methods to get model classes.

from django.db.models.loading import get_models, get_app
app = get_app('myappname')
models = get_models(app)
Daniel Roseman