peewee是python对sql很好对一个封装
操作一个数据库表,必须对应一个model,包含各种Field对应数据表字段
peewee逻辑符只支持这三种,多个条件最好加上括号\red{peewee 逻辑符只支持这三种,多个条件最好加上括号}peewee逻辑符只支持这三种,多个条件最好加上括号
& #and
| #or
~ #not
- 增\red{增}增
create
bulk_create
save
insert
insert_many
batch_commit
insert_from
常用
单条插入:
model.insert(map).execute()
大量插入:非常精辟\red{大量插入:非常精辟}大量插入:非常精辟
from peewee import chunked
with db.atomic():
for batch in chunked(data, 100):
Person.insert_many(batch).execute()
批量插入通常会包装成事务来保证原子性atomic
python提供chunked来自动分块
- 删\red{删}删
model.delete().where(model.Name=='王五').execute()
- 改\red{改}改
model.update({'Name': '赵六', 'Remarks': 'abc'}).where(model.Name=='张三').execute()
对于批量数字更新更快的写法:
model.update(intField=model.intField+1).execute()
- 查\red{查}查
get
get_or_none
get_by_id
get_or_create
select
常用:
# 单个
result = model.select(model.Name, model.Age).where(model.Name == '张三')
# 多个
results = list(model.select(model.Name, model.Age).where(model.Name == '张三'))
查询数量:
cnt = model.select().where(model.Name == '张三').count()
排序和逆序:
result = model.select().where(model.Name == '张三').order_by(model.Age.asc())
result = model.select().where(model.Name == '张三').order_by(model.Age.desc())
如果大量分批次查询,不建议使用limit+offset方式\red{如果大量分批次查询,不建议使用limit+offset方式}如果大量分批次查询,不建议使用limit+offset方式
改用where Id>lastId方式会更快些\red{改用where\ Id > lastId 方式会更快些}改用where Id>lastId方式会更快些