Oejia 技术栈
首页
应用市场
方案
OE学院
分享
关于
编辑器
登录
在普通 Python 项目中使用 Django ORM 的方法
admin
on 2016-05-11
很简单,定义一个settings.py模块,文件名可以为其他,如:“orm_conf.py” ``` import os DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'data.db', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } INSTALLED_APPS = ( 'app', ) SECRET_KEY = '5=!nss_+^nvyyc_j(tdcf!7(_una*3gtw+_8v5jaa=)j0g^d_2' ``` 然后在使用ORM之前执行一次如下代码即可 ```python import os os.environ["DJANGO_SETTINGS_MODULE"] = "demo.orm_conf" ``` 其中 "demo.orm_config" 表示相对于当前工作目录的 settings模块路径,其实也就是保证能import。 这样就可以导入模型使用 Django ORM 方法快速操作数据库了 ```python from app.models import A items = A.objects.all() ``` 注意:如上表示在app子目录下含有models模块,其中定义了我们要使用的模型,而且在settings模块的INSTALLED_APPS配置项中加入“app” 实际效果如下: ![](/files/201605/11190013492_django.png) ## 最简方法 经过笔者验证,还有一种更简单的方法,无需settings模块文件 ```python from django.conf import settings settings.configure() settings.DATABASES = DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'data.db', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } settings.INSTALLED_APPS = ( 'app', ) from app.models import A items = A.objects.all() ``` 效果如下: ![](/files/201605/11191956481_django_best.png)
Information
在普通 Python 项目中使用 Django ORM 的方法
http://www.oejia.net/article/2daa767fa2e6ae1e82e2d38032b5fb71
http://www.oejia.net/raw/2daa767fa2e6ae1e82e2d38032b5fb71
admin
on 2016-05-11
Category
Django
Related
2017-12-26 :
Odoo 前端开发可用的内置JS功能介绍
2018-06-13 :
微信模块 Oejia_wx v0.5.2 发布,优化配置且增加直发微信消息UI功能
2018-03-23 :
Celery 配置项大全
2017-03-19 :
Log
2016-01-17 :
关于Django框架的ContentType模型
2014-12-23 :
MoSys详细说明文档
2017-02-15 :
关于 Odoo 的模板引擎 Qweb
2018-08-31 :
Odoo 中的 domain 的解析及各种使用例子
2019-03-08 :
Odoo 菜单美化模块 oejia_menu 常见问题处理
2022-02-03 :
用 VIM 操作 BOM 标记
官方订阅号
关注订阅实时了解我们更多分享
分类
(20)
Django (3)
DjangoX (13)
JS (2)
Nginx (1)
Odoo (134)
Python (1)
YouMd (3)
公告说明 (2)
前端 (2)
后端HTTP (7)
异常处理 (1)
桌面UI (1)
移动开发 (4)
About This Entry
常见 HTTP 状态码解析
Odoo 配置项全解
About This Blog
main index
to find recently
archives
to find all
标签
微信模块发布记录
微信模块
小程序商城
Web
Http
客服系统
审批OA
HTML5
OE商城
Markdown
DjangoX
解析
oeshop
PyQT
服系统
YouPBX
Excel
示例
md
markdown
Python
最近发布
OSError [Errno 5] Input/output error 异常处理
Odoo context 的常见使用示例
Odoo 符合国人菜单导航习惯的后台主题,支持最新的Odoo17、16等版本,支持企业版!
Odoo 官方应用市场开启 Odoo17 应用的发布!增加了行业应用专栏
Odoo商城模块 Oejia_weshop v1.2 发布,多商户、分销增强,增加商家端!
处理 Error Failed to download metadata for repo ‘appstream‘ Cannot prepare internal mirrorlist
Odoo 16 关键变化 change the term "acquirer" to "provider"
企业微信错误码 81013 的排查与处理
微信模块 Oejia_wx v0.6.7 发布,支持 Odoo16 及新的Websocket消息模式
Friend Links
Oejia技术梦博客分享
YouMd,爱上MarkDown
Mole轻量级wsgi架子