对象关系模型 pony 参考

近期使用了python 的 orm ——pony,特记录以下供参考:

pony与其它的orm相比,可谓别具一格,显得有点另类,主要以迭代器方式实现,写起来觉得与SQL无关,更像基本的纯python代码;而且其官方文档清晰。

一、使用pony的基本步骤

1.定义orm模型

from pony.orm import *

db = Database()

class Person(db.Entity):
    name = Required(str, 8)
    age = Required(int)

2.绑定数据库

pony同时支持四种数据库哦,即Sqlite、Mysql、PostgreSQL、Oracle。

db.bind(provider = 'sqlite',filename='a.db',create_db = True)
db.generate_mapping(create_tables=True)
3.查询操作
p = Person(name='John',age=23)
commit()                                #提交
select(p for p in Person if p.age>13)
p.age=15
commit()
p.delete()
commit()

二、重要参考

1.定义列可使用Required/Optional/PrimaryKey/Set等。Set用于定义关系。

2.数据类型常用的主要有str/int/float/Decimal/datetime/date/time/timedelta/bool/Json/bytes。

3.数据类型的常用可选参数:unique/auto(主键可用)/autostrip/column(指定列名)/default(numeric|str|function)/max/min/py_check(function)/reverse/size(int)。

4.可定义类属性_table_自定义表名。

5.实体类中可定义钩子方法after_delete/after_insert/after_update/before_delete/before_insert/before_update。

6.关系的定义

# 1-1
class Person(db.Entity):
    passport = Optional("Passport")

class Passport(db.Entity):
    person = Required(Person)

# 1-n
class Order(db.Entity):
    items = Set('OrderItem')

class OrderItem(db.Entity):
    order = Required(Order)
    # order = Optional(Order)

# n-n

class Stud(db.Entity):
    select = Set('Course')

class Course(db.Entity):
    stud = Set(Order)

7.绑定数据库(要安装指定的数据库连接库)

#Postgresql
db.bind(provider='postgres',user='',password='',host='',database='')
#Mysql
db.bind(provider='mysql',user='',passwd='',host='',db='')

8.可以使用db_session作为装饰器或上下文管理器进入数据库的增、删、改操作而不用显式调用commit();

9.查询

#用主键查询单个实体
Person[2]
#用具有unique属性查询
Person.get(name='John')
#有多个结果的查询
#返回迭代器,可以迭代处理结果
select(p for p in Person if p.age > 10)
#返回列表
select(p for p in Person if p.age > 10)[:]
#返回指定页
select(p for p in Person if p.age > 10).page(1,pagesize=10)
#返回查询得到的首个对象(无则返回None)
select(p for p in Person if p.age > 10).first()
#返回查询得到对象的属性的迭代器
select(p.name for p in Person if p.age > 10)
#修改对象属性
p.age=19
p.set(age=19,...)
p.set(**{age:19})
此外,关于数据查询中的一些聚合函数也可以使用。


猜你喜欢

转载自blog.csdn.net/cloveses/article/details/79354458
今日推荐