"Peewee是一个简单而小型的ORM。它几乎没有(但富有表现力)概念, 使其易于学习且使用直观".这是官网的介绍,那么什么是“ORM”呢?
ORM:对象关系映射(Object Relational Mapping)是通过使用描述对象和数据库之间映射的元数据, 将面向对象语言程序中的对象自动持久化到关系数据库中。 本质上就是将数据从一种形式转换到另外一种形式。 这也同时暗示着额外的执行开销; 然而,如果ORM作为一种中间件实现,则会有很多机会做优化,而这些在手写的持久层并不存在。 更重要的是用于控制转换的元数据需要提供和管理; 但是同样,这些花费要比维护手写的方案要少; 而且就算是遵守ODMG规范的对象数据库依然需要类级别的元数据。
安装与测试
可用 pip3 install peewee
方式安装peewee库。
from peewee import *
在 Debian / Ubuntu 中通过命令安装:
sudo apt install python3-peewee
Peewee附带了几个C扩展名的源文件 ,如果可用Cython的话,它们也会被构建。 Sqlite扩展,包括SQLite日期操作功能的Cython实现, REGEXP运算符和全文搜索结果排名算法。 这些扩展为SQLite数据库用户提供了附加功能并提高了性能。 Peewee将尝试提前确定是否已安装SQLite3, 并且仅当系统上有SQLite共享库时才构建SQLite扩展。
db = SqliteDatabase('xx_people.db')
class Person(Model):
name = CharField()
birthday = DateField()
class Meta:
database = db
现在有了模型,接下来连接到数据库。
db.connect()
True
创建表,命名为Person。
db.create_tables([Person,])
from datetime import date
uncle_bob = Person(name='Bob', birthday=date(1960, 1, 15))
uncle_bob.save()
1
也可以通过调用create()
方法来添加数据信息,
该方法返回模型实例:
grandma = Person.create(name='Grandma', birthday=date(1935, 3, 1))
herb = Person.create(name='Herb', birthday=date(1950, 5, 5))
p = Person.select().where(Person.name == 'Bob').get()
print(p)
1
for person in Person.select():
print(person.name)
Bob Grandma Herb
bob = Person.update({Person.name: 'Bobbbb'}).where(Person.name == 'Bob')
bob.execute()
1
for person in Person.select():
print(person.name)
Bobbbb Grandma Herb
在这个基础上再添加一个字段。
bob = Person(name='Bobbbb', is_relative=False)
bob.id = 1
bob.save()
1
bob.delete_instance()
1
for person in Person.select():
print(person.name)
Grandma Herb
delete_instance()
返回值是从数据库中删除的行数。