我想运行一个脚本来填充我的数据库.我想通过Django数据库API访问它.
唯一的问题是我不知道我需要导入什么才能获得访问权限.
怎么能实现这一目标?
也导入您的设置模块
import os os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings" from mysite.polls.models import Poll, Choice
应该做的伎俩.
这就是我在一个数据加载脚本的顶部.
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
这应该在您在脚本中执行其他操作之前执行.
另一种方法是使用fixture和manage.py.虽然如果您只是尝试完成批量数据加载来初始化数据库,这应该可以正常工作.
另外,根据您的工作情况,您可能也可能不希望在一次交易中完成所有操作.取消注释上面的事务行并构造与此类似的代码.
transaction.enter_transaction_management() try: #Do some stuff transaction.commit() finally: transaction.rollback() pass transaction.leave_transaction_management()
如果在项目目录中使用脚本的shell
参数,则manage.py
不必手动导入设置:
$ 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 * >>>
对于非交互式使用,您可以实现自定义命令并运行它manage.py
.