【发布时间】:2010-09-15 23:36:16
【问题描述】:
我想运行一个脚本来填充我的数据库。我想通过 Django 数据库 API 访问它。
唯一的问题是我不知道我需要导入什么才能访问它。
如何做到这一点?
【问题讨论】:
我想运行一个脚本来填充我的数据库。我想通过 Django 数据库 API 访问它。
唯一的问题是我不知道我需要导入什么才能访问它。
如何做到这一点?
【问题讨论】:
最干净的解决方案是添加 django 扩展。
(virt1)tsmets@calvin:~/Documents/prive/rugby-club/proposal/kitu$ yolk -l Django - 1.3.1 - 活跃 Pygments - 1.4 - 活跃 Python - 2.6.5 - 积极开发 (/usr/lib/python2.6/lib-dynload) django-extensions - 0.7.1 - 活跃 pip - 1.0.2 - 活跃 setuptools - 0.6c11 - 活动 wsgiref - 0.1.2 - 积极开发 (/usr/lib/python2.6) 蛋黄 - 0.4.1 - 活跃然后使用 runscript 命令扩展可能的命令列表。
【讨论】:
如果您在项目目录中使用manage.py 脚本的shell 参数,则不必手动导入设置:
$ cd mysite/
$ ./manage.py shell
Python 2.5.2 (r252:60911, Jun 10 2008, 10:35:34)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from myapp.models import *
>>>
对于非交互式使用,您可以实现 custom command 并使用 manage.py 运行它。
【讨论】:
这是我的数据加载脚本顶部的内容。
import string
import sys
try:
import settings # Assumed to be in the same directory.
#settings.DISABLE_TRANSACTION_MANAGEMENT = True
except ImportError:
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
#Setup the django environment with the settings module.
import django
import django.core.management
django.core.management.setup_environ(settings)
from django.db import transaction
这一切都应该在您在脚本中执行很多其他操作之前执行。
另一种方法是使用fixtures和manage.py。虽然如果您只是尝试完成批量数据加载以初始化数据库,这应该可以正常工作。
还取决于您正在做什么,您可能希望或可能不想在一次交易中完成所有操作。取消注释上面的事务行,并像这样构建您的代码。
transaction.enter_transaction_management()
try:
#Do some stuff
transaction.commit()
finally:
transaction.rollback()
pass
transaction.leave_transaction_management()
【讨论】:
也导入您的设置模块
import os
os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings"
from mysite.polls.models import Poll, Choice
应该可以解决问题。
【讨论】:
除了您自己的模型文件之外,您还需要导入您的设置模块。
【讨论】: