python - 如何在 Django 之外使用 Django 模型?

标签 python django python-3.x django-models

正在关注 this指南,我可以通过调用 python main.py 在 Django 之外使用具有以下文件结构的模型。

├── data
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   └── models.py
├── main.py
├── manage.py
└── settings.py

main.py 看起来像这样:

import os, django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')

django.setup()
from data.models import Foo, Bar #...

print(Foo.objects.all()) #this works fine

我想做的是将它变成一个名为 db 的“包”,如下所示:

    ├── data
    │   ├── __init__.py
    │   ├── migrations
    │   │   └── __init__.py
    │   └── models.py
    ├── __init__.py 
    ├── manage.py
    └── settings.py

db 包的 __init__.py 中,我想这样做:

import os, django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')

django.setup()
from data.models import Foo, Bar # ...
from django.db import connection

__all__ = [
    'connection',
    'Foo',
    'Bar', 
    #...
]

所以我可以从 test.py(与 db 位于同一目录中)调用 db 包,如下所示:

import db

print(db.Foo.objects.all()) # this throws an error "no module named data"

或者像这样:

from db import Foo

print(Foo.objects.all()) # this throws an error "no module named settings"

有没有一种方法我可以使用 Django 的模型而无需调用: os.environ.setdefault('DJANGO_SETTINGS_MODULE', '设置') django.setup()

在每个使用模型的页面上?

我在这里错过了什么?

最佳答案

如果您查看如何 Django apps are loaded我认为您需要在应用程序的 models.pymodels/init.py 而不是 db/__init__.py 中运行设置/p>

When Django starts, django.setup() is responsible for populating the application registry.

setup(set_prefix=True) Configures Django by:

Loading the settings. Setting up logging. If set_prefix is True, setting the URL resolver script prefix to FORCE_SCRIPT_NAME if defined, or / otherwise. Initializing the application registry. This function is called automatically:

When running an HTTP server via Django’s WSGI support. When invoking a management command. It must be called explicitly in other cases, for instance in plain Python scripts.

The application registry is initialized in three stages. At each stage, Django processes all applications in the order of INSTALLED_APPS.

First Django imports each item in INSTALLED_APPS.

If it’s an application configuration class, Django imports the root package of the application, defined by its name attribute. If it’s a Python package, Django creates a default application configuration.

At this stage, your code shouldn’t import any models!

In other words, your applications’ root packages and the modules that define your application configuration classes shouldn’t import any models, even indirectly.

Strictly speaking, Django allows importing models once their application configuration is loaded. However, in order to avoid needless constraints on the order of INSTALLED_APPS, it’s strongly recommended not import any models at this stage.

Once this stage completes, APIs that operate on application configurations such as get_app_config() become usable.

Then Django attempts to import the models submodule of each application, if there is one.

You must define or import all models in your application’s models.py or models/__init__.py. Otherwise, the application registry may not be fully populated at this point, which could cause the ORM to malfunction.

Once this stage completes, APIs that operate on models such as get_model() become usable.

Finally Django runs the ready() method of each application configuration.

关于python - 如何在 Django 之外使用 Django 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55247878/

相关文章:

python - 预测事件顺序的机器学习算法?

mysql - Django 测试 django.db.utils.ProgrammingError : (1146, "Table ' DB.Table'不存在")

django - 我正在寻找 django mptt 的工作示例

python - unittest 的 setUpClass 类方法能否返回一个值以在其他测试中使用?

python-3.x - MatplotlibDeprecationWarning 与 Pyinstaller .exe

python - 嵌套列表代码中缺少第一个列表

python indeed api 不会返回超过 1025 个结果

python - 在字符串python中查找重复的单词

python - 如何使用 html 和 css 在 python 中连续显示 3 个帖子?它现在显示最后一个帖子下的每个帖子

python - 如何键入一个函数返回另一个函数的提示?