用于 Django 应用程序的 Python 脚本,无需使用 manage.py shell 即可访问模型 [英] Python script for Django app to access models without using manage.py shell
问题描述
我正在编写一个脚本来将一些模型对象导入到我的 django 应用程序使用的数据库中.过去,我通过运行 ./manage.py shell
然后 import myscript
解决了这个问题.我确定有更好的方法.我希望能够使用 python scriptname.py
从我的 HD 上的任何位置调用脚本,并且在该脚本的前几行中,它将执行任何必要的导入/其他操作,以便它可以访问模型对象并表现得就像使用 manage.py shell
运行一样.
I'm writing a script to import some model objects into the database my django application uses. In the past I've solved this by running ./manage.py shell
and then 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
.
我需要在脚本中添加什么来实现这一点?
What do I need to add to my script to achieve this?
基于@Melug 的回答,并添加了动态设置 Python 路径以解决问题的我的 HD 上的任何地方"部分:
Based on @Melug's answer, with addition of dynamically setting Python path to address the 'anywhere on my HD' part of the question:
import sys
sys.path.append('c:\my_projec_src_folder')
from myproject import settings
from django.core.management import setup_environ
setup_environ(settings)
推荐答案
需要先设置django环境:
You need to setup django environment first:
from your_project import settings
from django.core.management import setup_environ
setup_environ(settings)
最后导入你的模型,一切都像 django 一样.
At last import your models, everything goes just like django.
这篇关于用于 Django 应用程序的 Python 脚本,无需使用 manage.py shell 即可访问模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!