Python 获取 Django 中所有已安装应用程序及其属性的列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4111244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:18:31  来源:igfitidea点击:

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

pythondjangodjango-models

提问by bnabilos

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.

在我的 Django 网站中,我创建了一个与网站中安装的其他应用程序动态交互的类。我必须对每个应用程序的每个字段进行操作。

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 ?

所以我想将所有已安装应用程序的名称保存在一个列表中并获取每个应用程序的属性。有没有办法使用迭代器或其他方法来做到这一点?

采纳答案by Matthew Schinckel

Under Django 1.7 and above (thanks Colin Anderson):

在 Django 1.7 及更高版本下(感谢 Colin Anderson):

from django.apps import apps
apps.get_models()

Under Django 1.6 and below.

在 Django 1.6 及以下版本下。

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.

我相信旧的功能仍然有效。

回答by André Caron

The list of installed applications is defined in settings.INSTALLED_APPS. It contains a tuple of strings, so you can iterate on it to access each application's name.

已安装的应用程序列表在 中定义settings.INSTALLED_APPS。它包含一个字符串元组,因此您可以对其进行迭代以访问每个应用程序的名称。

However, I'm not sure what you mean by each application's attributesand fields.

但是,我不确定您所说的每个应用程序的attributesfields是什么意思。

回答by Paulo Scardine

[edit]

[编辑]

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

从 Django 1.7 开始,settings.INSTALLED_APPS不鼓励访问:“您的代码不应直接访问 INSTALLED_APPS。改用 django.apps.apps。” – 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.pyfile.

所有应用程序都在settings.py文件中注册。

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 printcall).

为了使用新的打印函数而不是旧 Python 中的打印语句,您可能必须发出 a from __future__ import print_function(或仅更改包含print调用的行)。

回答by Zulu

You can retrieve installed apps like that (in interpreter) :

您可以像这样检索已安装的应用程序(在解释器中):

>>> from django.conf import settings
>>> [app for app in settings.INSTALLED_APPS
     if not app.startswith("django.")]
['myapp1', 'myapp2', 'myapp3']

回答by Cj Welborn

To get the actual appsthemselves (not just names), this is what I came up with:

为了获得实际的应用程序本身(不仅仅是名称),这就是我想出的:

from django.conf import settings
from django.utils.module_loading import import_module
apps = [import_module(appname) for appname in settings.INSTALLED_APPS]

Though you may want to do some error handling, or filtering.

尽管您可能想要进行一些错误处理或过滤。

回答by caio

Tested with Django 1.9:

用 Django 1.9 测试:

from django.test.runner import DiscoverRunner
from django.test import override_settings
from django.apps import apps


class DiscoverRunnerNoMigrations(DiscoverRunner):
    def run_tests(self, *args, **kwargs):
        app_labels = [a.label for a in apps.app_configs.values()]
        migration_modules = dict.fromkeys(app_labels)

        with override_settings(MIGRATION_MODULES=migration_modules):
            return super(DiscoverRunnerNoMigrations, self).run_tests(*args,
                                                                     **kwargs)

Update your settings to point to this test runner.

更新您的设置以指向此测试运行程序。

Running this with --keepdb is real fast.

使用 --keepdb 运行它真的很快。

回答by Stas Teitel

Works on Django 1.11+ (I'm working on Django 2.2)

适用于 Django 1.11+(我正在使用 Django 2.2)

from django.conf import settings
from django.apps import apps

# get complete list of all apps
list_of_apps = [apps.get_app_config(app_name.split('.')[-1]) \
                for app_name in settings.INSTALLED_APPS]
# app_name.split('.')[-1] we need, because some system apps has dots in name
# like 'django.contrib.admin', and app_label is 'admin'

# get list of models for one specific app. For example first app in list_of_apps
models_list = [model for name, model in list_of_apps[0].models.items() \
               if not model._meta.auto_created]
# we outfiltered auto_created models, because they are not in models.py
# and had been created automatically by Django