我正在尝试从另一个 python 脚本访问我的 Django (v1.10) 应用程序数据库,但在这样做时遇到了一些问题。
这是我的文件和文件夹结构:
store
store
__init.py__
settings.py
urls.py
wsgi.py
store_app
__init.py__
admin.py
apps.py
models.py
...
db.sqlite3
manage.py
other_script.py
根据 Django's documentations我的 other_script.py
看起来像这样:
import django
from django.conf import settings
settings.configure(DEBUG=True)
django.setup()
from store.store_app.models import MyModel
但它会产生运行时错误:
RunTimeError: Model class store.store_app.models.MyModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
我应该注意到我的 INSTALLED_APPS
列表包含 store_app
作为它的最后一个元素。
如果我尝试传递这样的配置:
import django
from django.conf import settings
from store.store_app.apps import StoreAppConfig
settings.configure(StoreAppConfig, DEBUG=True)
django.setup()
from store.store_app.models import MyModel
我明白了:
AttributeError: type object 'StoreAppConfig has no attribute 'LOGGING_CONFIG'.
如果我编辑 settings.py
并添加 LOGGING_CONFIG=None
我会收到另一个关于另一个缺失属性的错误,等等。
任何建议将不胜感激。
最佳答案
试试这个
import sys, os, django
sys.path.append("/path/to/store") #here store is root folder(means parent).
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "store.settings")
django.setup()
from store_app.models import MyModel
您可以在系统中的任何位置使用此脚本。
关于python - Django 独立脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39723310/