python django框架orm_在Python的Django框架上部署ORM库的教程

文章主要介绍Python的ORM库情况,除SQLAlchemy外还有很多可选库。着重介绍了SQLObject,它是介于SQL数据库和Python之间的映射对象,遵循LGPL许可,提供基于Python对象的查询语言。还给出了安装代码及创建表、插入记录的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python ORM 概览

作为一个美妙的语言,Python 除了 SQLAlchemy 外还有很多ORM库。在这篇文章里,我们将来看看几个流行的可选ORM 库,以此更好地窥探到Python ORM 境况。通过写一段脚本来读写2个表 ,person 和 address 到一个简单的数据库,我们能更好地理解每个ORM库的优缺点。

SQLObject

SQLObject 是一个介于SQL数据库和Python之间映射对象的Python ORM。得益于其类似于Ruby on Rails的ActiveRecord模式,在编程社区变得越来越流行。首个 SQLObject在2002年十月发布。它遵循LGPL许可。

在 SQLObject 中,数据库概念是通过与 SLQAlchemy 非常类似的的一种方式映射到Python的,表映射成类,行作为实例而字段作为属性。它同时提供一种基于Python对象的查询语言,这使得SQL 更加抽象, 从而为应用提供了数据库不可知性(译注:应用和数据库分离)

$ pip install sqlobject

Downloading/unpacking sqlobject

Downloading SQLObject-1.5.1.tar.gz (276kB): 276kB downloaded

Running setup.py egg_info for package sqlobject

warning: no files found matching '*.html'

warning: no files found matching '*.css'

warning: no files found matching 'docs/*.html'

warning: no files found matching '*.py' under directory 'tests'

Requirement already satisfied (use --upgrade to upgrade): FormEncode>=1.1.1 in /Users/xiaonuogantan/python2-workspace/lib/python2.7/site-packages (from sqlobject)

Installing collected packages: sqlobject

Running setup.py install for sqlobject

changing mode of build/scripts-2.7/sqlobject-admin from 644 to 755

changing mode of build/scripts-2.7/sqlobject-convertOldURI from 644 to 755

warning: no files found matching '*.html'

warning: no files found matching '*.css'

warning: no files found matching 'docs/*.html'

warning: no files found matching '*.py' under directory 'tests'

changing mode of /Users/xiaonuogantan/python2-workspace/bin/sqlobject-admin to 755

changing mode of /Users/xiaonuogantan/python2-workspace/bin/sqlobject-convertOldURI to 755

Successfully installed sqlobject

Cleaning up...

>>> from sqlobject import StringCol, SQLObject, ForeignKey, sqlhub, connectionForURI

>>> sqlhub.processConnection = connectionForURI('sqlite:/:memory:')

>>>

>>> class Person(SQLObject):

... name = StringCol()

...

>>> class Address(SQLObject):

... address = StringCol()

... person = ForeignKey('Person')

...

>>> Person.createTable()

[]>>> Address.createTable()

[]

上面的代码创建了2个简单的表:person 和 address 。为了创建和插入记录到这2个表,我们简单实例化一个person 实例和 一个 address 实例:

>>> p = Person(name='person')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值