2012-05-12 57 views
0

我尝试将数据填充到我的数据库中,我想使用django API来这样做。我写了一个python模块,可以让我很轻松地做到这一点。从django shell运行python模块(manage.py)

但是,在django shell(manage.py)中,似乎无法运行我的“populate.py”文件。

是否有可能从django shell运行我的populate.py?或者,我是否应该运行一个普通的Python终端并导入必要的django组件?无论如何,我会非常感谢一些指标。

+1

你是否尝试从django shell内导入填充?导入填充; populate.main()或类似的东西... – vasek1

回答

1

这里是我的命令行运行的Django的东西标准包装。如果您有要运行的cron脚本,这也很有用。

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

import os, sys 
# If this script lives in a child directory of the main project directory 
# uncomment the following 2 lines: 
#dir_parent = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) 
#sys.path.insert(0, dir_parent) 

from django.core.management import setup_environ 
import settings 
setup_environ(settings) 

from django.db import transaction 

# import whatever you like from app.models or whatever 
# do random stuff. 

# If you are *changing* database records, 
# wrap your database code either in: 
@transaction.commit_manually 
def foo(): 
    ... stuff 
    transaction.commit() 

# OR end you script with: 
transaction.commit_unless_managed() 

更新评论:

上面提到的变量不是file,它是__file__(即2下划线file和2多个下划线)。这总是由Python解释器设置为它所在文件的完整路径。如注释所示,如果此脚本位于主目录的子目录中,则文件名的目录目录将为您提供主项目目录的目录名称,并将其添加到sys.path将确保所有导入工作正常。如果脚本在主目录中生存,并从那里执行它,则不需要这样做。

+0

谢谢!但是,我现在正在收到“Traceback(最近呼叫的最后一个): 文件”“,第1行,在 dir = os.path.dirname(os.path.dirname(os.path.realpath(__ file__) )) NameError:名称'__file__'未定义“ – snakesNbronies

+0

请参阅我的更新答案。 –

+0

谢谢!我只是有一些语法问题。现在工作。但是,我仍然决定将其作为自定义django-admin命令进行打包,以避免将来需要此类事物。 – snakesNbronies

0

尝试django-extensions它有一个脚本目录中的脚本命令。

奇怪的命令似乎从主要文件丢失,但如果你谷歌django扩展脚本你会发现的例子和文件。

相关问题