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 ?
Under Django 1.7 and above (thanks Colin Anderson):
from django.apps import apps apps.get_models()
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__, [x.name for x in model._meta.fields]
I believe the older function still works.
Since Django 1.7, accessing
settings.INSTALLED_APPSis 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
In : from django.conf import settings In : 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 : from pprint import pprint In : for app_name in settings.INSTALLED_APPS: try: module_ = __import__(app_name) except ImportError: pass map(print, ['=' * 80, "MODULE: "+app_name, '-' * 80]) pprint(module_.__dict__)
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