Hobhouse
Hobhouse

Reputation: 16303

How do I list all classes of a given type in a python file?

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)?

Upvotes: 0

Views: 252

Answers (4)

Guillaume Algis
Guillaume Algis

Reputation: 11016

In recent versions of Django the django.db.models.loading apparently no longer exists, but you can list the models of an app with :

from django.apps import apps

app = apps.get_app_config("your_app_name")
models = app.get_models()

for model in models:
    print(model)

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 600059

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)

Upvotes: 4

mg.
mg.

Reputation: 8012

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)]

Upvotes: 2

user25148
user25148

Reputation:

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.

Upvotes: 1

Related Questions