如何编写与Django模块一起使用的独立Python脚本? [英] How to write a stand-alone Python script working with Django modules?
问题描述
在PyCharm中,我创建了一个空白的新Django应用.创建了一些模型并发布了 manage.py makemigrations
和 manage.py migration
之后,我试图编写一个独立的脚本,用初始数据填充数据库.在其进口中,我写道:
In PyCharm, I created a blank new Django app. Having created some models and issued manage.py makemigrations
and manage.py migrate
, I tried to write a standalone script that would populate the database with initial data. In its imports I wrote:
from MyApp.models import Model1, Model2, …
遗憾的是,在PyCharm中运行此脚本会引发异常: django.core.exceptions.ImproperlyConfigured:请求的设置为DEFAULT_TABLESPACE,但未配置设置.在访问设置之前,您必须定义环境变量DJANGO_SETTINGS_MODULE或调用settings.configure().
Sadly, running this script in PyCharm throws an exception: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
我用Google搜索了该异常,并在 https://stackoverflow.com/a/27455703/4385532 中找到了答案>建议将其放在脚本的顶部:
I Googled this exception, and found an answer in SO https://stackoverflow.com/a/27455703/4385532 advising to put this in the top of my script:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
所以我做到了.遗憾的是,这并不能解决问题.现在,我迎来了另一个例外: django.core.exceptions.AppRegistryNotReady:模型尚未加载.
So I did. Sadly, this didn’t fix the issue. Now I am greeted with another exception:
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
我该怎么办?
推荐答案
请确保您也这样做:
import django
django.setup()
加载模型.
文档: 查看全文