我已经看到很多关于如何在项目之外使用django模型的答案。但我没有成功。我试图实现this回答,但是我收到了错误。我创建了一个新文件" 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 *
当我运行此脚本时,出现错误。
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.
有人可以帮我这个吗?
答案 0 :(得分:8)
您需要的是可导入的设置。
import os
import django
os.environ["DJANGO_SETTINGS_MODULE"] = 'project.settings'
django.setup()
from .models import
另一种通过django shell调用脚本的方法:
python manage.py shell < script.py
答案 1 :(得分:1)
正如例外情况所说,没有安装任何应用程序,你还没有型号。
from django.conf import settings
settings.configure(
DATABASE_ENGINE = 'sqlite3',
DATABASE_NAME = '/home/shivam/study/Python/automation/project/db.sqlite3',
# ....
INSTALLED_APPS=["myapp","myotherapp"]
)
from myapp.models import *
答案 2 :(得分:0)
以下解决方案来自位于manage.py所在目录中的脚本:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showEventDetail" {
if let IndexPath = self.tableView.indexPathForSelectedRow {
// we're segueing to a Tab Bar Controller
if let tabBarVC = segue.destination as? UITabBarController {
// get the first view controller of the Tab Bar Controller
// *that* is where you want to "pass" your data
if let controller = tabBarVC.viewControllers?.first as? eventDetailViewController {
// either should work
controller.inTradeShowID = (events?[IndexPath.row].tradeshowID!)!
controller.viaSegue = (events?[IndexPath.row].tradeshowID!)!
} //end if let controller = tabBarVC.viewControllers?.first as? eventDetailViewController
} //end if let tabBarVC = segue.destination as? UITabBarController
} //end if let IndexPath = self.tableView.indexPathForSelectedRow
} //end if segue.identifier == "showEventDetail"
}
将Demo替换为您的应用名称,并为您的应用添加正确的数据库配置。这个解决方案适用于Django 1.9。