【问题标题】:Django: manipulating database with script; importation errorDjango:用脚本操作数据库;输入错误
【发布时间】:2018-09-03 20:48:10
【问题描述】:

我正在阅读 Django 教程,想尝试使用 python 脚本操作数据库,但遇到了问题

我的脚本:

from polls.models import Question, Choice
from django.utils import timezone
import numpy as np
#Questions
nquestions=3
q=np.empty([nquestions, 10], dtype=object)
qtext=q
qtext[0]="What's up?"
qtext[1]="What's new?"
qtext[2]="What's old?"

#Choices
q[0,1]="Not much"
q[0,2]="The sky"
q[1,1]="This question"
q[1,2]="This answer"
q[2,1]="No more originality"
q[2,2]="xxxxxxx"


#Check if exists and apply
for i in range(0, len(q)):
    q[i,0]=Question(question_text=qtext[i], pub_date=timezone.now())
    if Question.objects.filter(question_text=qtext[i]).exists():
        pass
    else:
        q[i,0].question_text=qtext[i]
        q[i,0].save()
        alen=len(q[i][q[i] != np.array(None)])
        for ii in range(0, alen-1):
            q[i,0].choice_set.create(choice_text=q[i,ii+1], votes=0)

我收到错误 django.core.exceptions.appregistrynotready 尚未加载应用程序。我正在从终端运行脚本,它位于包含 polls 文件夹的文件夹中(比 modules.py 高一级,我正在尝试导入)。

如果我第一次在终端中运行,编写脚本的内容是可行的:python manage.py shell。有没有办法让我通过 Djangos API 运行脚本来操作数据库,还是我必须手动输入信息或通过 post 发送请求?

【问题讨论】:

  • 尝试通过 django shell 运行

标签: python django django-models


【解决方案1】:

您需要先设置DJANGO_SETTINGS_MODULE 环境变量并调用django.setup(),然后才能导入模型。

import os
import django
# Change mysite if your project has a different name 
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
django.setup()

from polls.models import Question, Choice
...

请参阅the docs 了解更多信息。

另一种选择是写一个custom management command。当您使用manage.py 运行管理命令时,您不必设置DJANGO_SETTINGS_MODULE 或调用django.setup()

【讨论】:

    猜你喜欢
    • 2021-03-12
    • 2021-04-24
    • 2014-12-09
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 2021-07-06
    相关资源
    最近更新 更多