Django:如何使用我的模型类与Django之外的数据库进行交互? [英] Django: How can I use my model classes to interact with my database from outside Django?

查看:81
本文介绍了Django:如何使用我的模型类与Django之外的数据库进行交互?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个使用Django应用程序模型与我的数据库进行交互的脚本。但是,我希望能够从命令行或通过cron运行这个脚本。我需要导入什么来允许这个?

I'd like to write a script that interacts with my DB using a Django app's model. However, I would like to be able to run this script from the command line or via cron. What all do I need to import to allow this?

推荐答案

您需要设置Django环境变量。这些告诉Python您的项目是什么,以及设置模块的名称(设置模块中的项目名称是可选的):

You need to set up the Django environment variables. These tell Python where your project is, and what the name of the settings module is (the project name in the settings module is optional):

import os

os.environ['PYTHONPATH'] = '/path/to/myproject'
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'

现在您应该能够访问模型:

Now you should be able to access the models:

from myproject.models import MyModel

all_my_models = MyModel.objects.all()

这篇关于Django:如何使用我的模型类与Django之外的数据库进行交互?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆