脚本化Django [英] Scripting Django
问题描述
编辑
我需要在另一台服务器中使用复杂的数据库操作,所以像自定义AppCommands或者调用Djando页面这样的解决方案也不会真的有效。
谢谢
一种方法是创建您的自己的管理命令。那么你可以从这样做这样的事情。你的crontab:
python manage.py my_command
另一种方法是确保Django,您的Django项目,并在需要时,第三方应用程序在您的PYTHONPATH上。然后,您可以使用几行代码访问数据库和ORM:
from django.core.management import setup_environ
从my_project导入设置
setup_environ(设置)
现在你可以执行以下操作:
from my_app.models import MyModel
all_objects = MyModel.objects.all()
what is the best way to write a python script (not to run within a Django server app) making use of Django settings, models, utilities etc and hence being able to operate on an app database from, say, a batch process?
EDIT
I need to use this within another server to make rather complex operations on the database, so solutions like custom AppCommands or invoking a Djando page won't really work
Thanks
One way to do this is to create your own management command. Then you can do something like this from e.g. your crontab:
python manage.py my_command
Another way is to make sure Django, your Django project and, when required, third party apps are on your PYTHONPATH. Then you can access the database and ORM using a few lines of code:
from django.core.management import setup_environ
from my_project import settings
setup_environ(settings)
Now you can e.g. do things like this:
from my_app.models import MyModel
all_objects = MyModel.objects.all()
这篇关于脚本化Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!