Peewee 使用

288 阅读3分钟

Peewee是一个简单小巧的Python ORM,它非常容易学习,并且使用起来很直观。

如果想快速入门,请参考官方的Quckstart

本文,只是写今天在使用过程中的一些记录。

基本知识

官方的Quckstart中,我了解到,Peewee中Model类、fieldsmodel实例与数据库的映射关系如下:

image.png

也就是说,一个Model类代表一个数据库的表一个Field字段代表数据库中的一个字段而一个model类实例化对象则代表数据库中的一行

至于Peewee的实现原理,我暂时没有看源代码,但觉得和廖雪峰老师的使用元类这个文章的例子实现类似。

实践

而使用过程,分成两步:

定义Model,建立数据库

在使用的时候,根据需求先定义好Model,然后可以通过create_tables()创建表,若是已经创建好数据库表了,可以通过python -m pwiz脚本工具直接创建Model。

第一种方式:

先定义Model,然后通过db.create_tables()创建或Model.create_table()创建表。

例如,我们需要建一个Person表,里面有namebirthdayis_relative三个字段,我们定义的Model如下:

from peewee import *

# 连接数据库
database = MySQLDatabase('test', user='root', host='localhost', port=3306)

# 定义Person
class Person(Model):
    name = CharField()
    birthday = DateField()
    is_relative = BooleanField()

    class Meta:
        database = database

然后,我们就可以创建表了

# 创建表
Person.create_table()

# 创建表也可以这样, 可以创建多个
# database.create_tables([Person])

其中,CharField、DateField、BooleanField等这些类型与数据库中的数据类型一一对应,我们直接使用它就行,至于CharField => varchar(255)这种转换Peewee已经为我们做好了 。

第二种方式:

已经存在过数据库,则直接通过python -m pwiz批量创建Model。
例如,上面我已经创建好了test库,并且创建了Person表,表中拥有idnamebirthdayis_relative字段。那么,我可以使用下面命令:

# 指定mysql,用户为root,host为localhost,数据库为test
python -m pwiz -e mysql -u root -H localhost --password test > testModel.py

然后,输入密码,pwiz脚本会自动创建Model,内容如下:

from peewee import *

database = MySQLDatabase('test', **{'charset': 'utf8', 'use_unicode': True, 'host': 'localhost', 'user': 'root', 'password': ''})

class UnknownField(object):
    def __init__(self, *_, **__): pass

class BaseModel(Model):
    class Meta:
        database = database

class Person(BaseModel):
    birthday = DateField()
    is_relative = IntegerField()
    name = CharField()

    class Meta:
        table_name = 'person'

操作数据库

操作数据库,就是增、删、改和查。

一、增

直接创建示例,然后使用save()就添加了一条新数据

# 添加一条数据
p = Person(name='waws520', birthday=date(1990, 12, 20), is_relative=True)
p.save()
二、删

使用delete().where().execute()进行删除,where()是条件,execute()负责执行语句。若是已经查询出来的实例,则直接使用delete_instance()删除。

# 删除姓名为perter的数据
Person.delete().where(Person.name == 'perter').execute()

# 已经实例化的数据, 使用delete_instance
p = Person(name='waws520', birthday=date(1990, 12, 20), is_relative=False)
p.id = 1
p.save()
p.delete_instance()
三、改

若是,已经添加过数据的的实例或查询到的数据实例,且表拥有primary key时,此时使用save()就是修改数据;若是未拥有实例,则使用update().where()进行更新数据。

# 已经实例化的数据,指定了id这个primary key,则此时保存就是更新数据
p = Person(name='waws520', birthday=date(1990, 12, 20), is_relative=False)
p.id = 1
p.save()

# 更新birthday数据
q = Person.update({Person.birthday: date(1983, 12, 21)}).where(Person.name == 'waws520')
q.execute()
四、查

单条数据使用Person.get()就行了,也可以使用Person.select().where().get()。若是查询多条数据,则使用Person.select().where(),去掉get()就行了。语法很直观,select()就是查询,where是条件,get是获取第一条数据。

# 查询单条数据
p = Person.get(Person.name == 'waws520')
print(p.name, p.birthday, p.is_relative)

# 使用where().get()查询
p = Person.select().where(Person.name == 'waws520').get()
print(p.name, p.birthday, p.is_relative)

# 查询多条数据
persons = Person.select().where(Person.is_relative == True)
for p in persons:
    print(p.name, p.birthday, p.is_relative)