0

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

4 Answers 4

4

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) 
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

@Max Shawabkeh: thanks for the correction. I was thinking about __dict__ and values and i did that stupid error.
1

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.

Comments

0

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) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.