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

时间:2021-11-27 20:21:45

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 ?

因此,我想将所有已安装应用程序的名称保存在一个列表中,并获取每个应用程序的属性。有一种方法可以使用迭代器或其他东西来实现这一点吗?

6 个解决方案

#1


57  

Under Django 1.7 and above (thanks Colin Anderson):

《被解救的姜戈》1.7及以上(谢谢科林·安德森):

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.

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

#2


16  

[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

从Django 1.7开始,访问设置。不鼓励INSTALLED_APPS:“你的代码永远不能直接访问INSTALLED_APPS。使用django.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.py file.

所有应用程序都在设置中注册。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 print call).

为了在旧的Python中使用新的print函数而不是print语句,您可能需要发出一个from __future__ import print_function(或者只修改包含print调用的行)。

#3


8  

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 attributes and fields.

然而,我不确定您所说的每个应用程序的属性和字段是什么意思。

#4


7  

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

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

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

#5


3  

To get the actual apps themselves (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.

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

#6


0  

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运行这个非常快。

#1


57  

Under Django 1.7 and above (thanks Colin Anderson):

《被解救的姜戈》1.7及以上(谢谢科林·安德森):

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.

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

#2


16  

[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

从Django 1.7开始,访问设置。不鼓励INSTALLED_APPS:“你的代码永远不能直接访问INSTALLED_APPS。使用django.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.py file.

所有应用程序都在设置中注册。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 print call).

为了在旧的Python中使用新的print函数而不是print语句,您可能需要发出一个from __future__ import print_function(或者只修改包含print调用的行)。

#3


8  

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 attributes and fields.

然而,我不确定您所说的每个应用程序的属性和字段是什么意思。

#4


7  

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

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

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

#5


3  

To get the actual apps themselves (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.

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

#6


0  

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运行这个非常快。