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

后端 未结 7 1348
一个人的身影
一个人的身影 2020-12-13 17:32

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 app

7条回答
  •  轮回少年
    2020-12-13 18:06

    [edit]

    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 settings.py 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:
        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 print call).

提交回复
热议问题