2008-10-08 84 views

回答

12

导入设置模块也

import os 
os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings" 

from mysite.polls.models import Poll, Choice 

应该做的伎俩。

0

除了您自己的模型文件,您还需要导入您的设置模块。

5

如果使用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 * 
>>> 

对于非交互使用,你可以实现一个custom command并运行它与manage.py

+0

除非我遗漏了一些东西,manage.py在Django 1.0中没有runscript子命令如果您使用自定义应用程序来提供此功能,则应该提及它。 – 2009-06-26 11:38:59

6

这是我在我的数据加载脚本的顶部。

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() 
+0

+1,当在我的项目的根目录下运行时,上面接受的答案不起作用,但是你的答案是! – pufferfish 2009-07-14 11:49:58

1

最干净的解决方案是添加django扩展。

 
(virt1)[email protected]:~/Documents/prive/rugby-club/proposal/kitu$ yolk -l 
Django   - 1.3.1  - active 
Pygments  - 1.4   - active 
Python   - 2.6.5  - active development (/usr/lib/python2.6/lib-dynload) 
django-extensions - 0.7.1  - active 
pip    - 1.0.2  - active 
setuptools  - 0.6c11  - active 
wsgiref   - 0.1.2  - active development (/usr/lib/python2.6) 
yolk   - 0.4.1  - active 

然后,可能的命令的列表随runcript命令一起扩展。

相关问题