I'm writing a script to import some model objects into the database my django application uses.
(我正在编写一个脚本,将一些模型对象导入到我的django应用程序使用的数据库中。)
In the past I've solved this by running ./manage.py shell
and then import myscript
. (过去,我已经通过运行./manage.py shell
并import myscript
解决了这一问题。)
I'm sure there's a better way. (我敢肯定有更好的方法。)
I'd like to be able to call a script from anywhere on my HD using python scriptname.py
, and in the first few lines of that script it would do whatever imports / other operations necessary so that it can access model objects and behave as though it was run using manage.py shell
. (我希望能够使用python scriptname.py
从HD的任何位置调用脚本,并且在该脚本的前几行中,它将执行任何必需的导入/其他操作,以便它可以访问模型对象并表现为尽管它是使用manage.py shell
运行的。)
What do I need to add to my script to achieve this?
(要实现此目的,我需要添加什么内容?)
EDIT:
(编辑:)
Based on @Melug's answer, with addition of dynamically setting Python path to address the 'anywhere on my HD' part of the question:
(基于@Melug的答案,此外还动态设置了Python路径以解决问题的“ HD上的任何地方”:)
import sys
sys.path.append('c:\my_projec_src_folder')
from myproject import settings
from django.core.management import setup_environ
setup_environ(settings)
ask by Trindaz translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…