pythondjangomodel

Django get list of models in application


So, i have a file models.py in MyApp folder:

from django.db import models
class Model_One(models.Model):
    ...
class Model_Two(models.Model):
    ...
...

It can be about 10-15 classes. How to find all models in the MyApp and get their names?

Since models are not iterable, I don't know if this is even possible.


Solution

  • From Django 1.7 on, you can use this code, for example in your admin.py to register all models:

    from django.apps import apps
    from django.contrib import admin
    from django.contrib.admin.sites import AlreadyRegistered
    
    app_models = apps.get_app_config('my_app').get_models()
    for model in app_models:
        try:
            admin.site.register(model)
        except AlreadyRegistered:
            pass