Get a list of all installed applications in Django and their attributes


In my Django website, I'm creating a class that interact dynamically with other applications installed in the website. I have to do a manipulation on each field of each application.

So I want to save the name of all installed applications in a list and get the attributes of each one. There is a way to do that using an iterator or something else ?

5/14/2016 9:29:54 AM

Accepted Answer

Under Django 1.7 and above (thanks Colin Anderson):

from django.apps import apps

Under Django 1.6 and below.

If you want all models, try:

from django.db.models import get_models

for model in get_models():
   # Do something with your model here
   print model.__name__, [ for x in model._meta.fields]

I believe the older function still works.

3/5/2018 3:04:23 PM


Since Django 1.7, accessing settings.INSTALLED_APPS is discouraged: "Your code should never access INSTALLED_APPS directly. Use django.apps.apps instead." – johanno

So the blessed way is:

from django.apps import apps

for app in apps.get_app_configs():
    print(app.verbose_name, ":")
    for model in app.get_models():
        print("\t", model)

Older version of this answer:

All applications are registered in the file.

In [1]: from django.conf import settings

In [2]: print(settings.INSTALLED_APPS)
['django.contrib.auth', 'django.contrib.contenttypes', 
 'django.contrib.sessions', 'django.contrib.sites', 
 'django.contrib.messages', 'django.contrib.staticfiles',
 'django.contrib.admin', 'raven.contrib.django']

You can import each application and list their attributes:

In [3]: from pprint import pprint

In [4]: for app_name in settings.INSTALLED_APPS:
        module_ = __import__(app_name)
    except ImportError:
    map(print, ['=' * 80, "MODULE: "+app_name, '-' * 80])

In order to use the new print function instead of the print statement in older Python you may have to issue a from __future__ import print_function (or just change the line containing the print call).

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow