从新脚本访问Django模型 [英] Accessing django models from a new script

查看:44
本文介绍了从新脚本访问Django模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在项目之外看到了许多关于如何使用Django模型的答案。但是我没有任何成功。我试图实现答案,但出现错误。我在应用程序内创建了一个新文件 script.py。

I have seen many answers on how to use django models outside the project. But I have no success with any. I was trying to implement this answer but I get an error. I have created a new file "script.py" inside my app.

script.py

script.py

from django.conf import settings
settings.configure(
    DATABASE_ENGINE = 'sqlite3',
    DATABASE_NAME = '/home/shivam/study/Python/automation/project/db.sqlite3',
    DATABASE_USER = '',
    DATABASE_PASSWORD = '',
    DATABASE_HOST = '',
    DATABASE_PORT = '',
    TIME_ZONE = 'America/New_York',
)
from models import *

运行此脚本时,出现错误。

When I run this script, I get an error.

Traceback (most recent call last):
  File "script.py", line 11, in <module>
    from models import *
  File "/home/shivam/study/Python/automation/project/videos/models.py", line 11, in <module>
    class video(models.Model):
  File "/home/shivam/study/Python/automation/env/local/lib/python2.7/site-packages/django/db/models/base.py", line 105, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/home/shivam/study/Python/automation/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 237, in get_containing_app_config
    self.check_apps_ready()
  File "/home/shivam/study/Python/automation/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

有人可以帮我吗?

推荐答案

您需要的是可导入的设置。

You need is importable settings.

import os
import django
os.environ["DJANGO_SETTINGS_MODULE"] = 'project.settings'
django.setup()
from .models import 

另一种通过django shell调用脚本的方法:

Another way call your script via the django shell:

python manage.py shell < script.py

这篇关于从新脚本访问Django模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆