python - peewee 各种用法

python - peewee 各种用法

Max.Bai

2020-03

目录

python - peewee 各种用法

0X00 背景

0X01 表结构

0X02 peewee子查询操作

0X03 modles混合sql 代码

0X04 peewee case用法

0X05 peewee OR 用法


0X00 背景

记录peewee 使用中需要的一些用法,包括子查询,混合sql脚本,case用法, OR用法

0X01 表结构

表结构 user
id  int             工号
name  varchar       名称


0X02 peewee子查询操作


mysql脚本:
 

select
t1.id,
t1.name
from (
select u.id, u.name
from user
where u.id > 1000
) as t1
where t1.id < 2000

首先你已经有了modle文件

# 子查询  id > 1000
subquery = user.select(user.id, user.name).where(user.id>1000)

# 外面查询
query = user.select(subquery.c.id, subquery.c.name).from_(subquery).where(subquery.c.id<2000).order_by(subquery.c.id)

0X03 modles混合sql 代码


当peewee支持不了的时候,可能需要写mysql脚本, 就需要用到SQL类

比如
SQL("'string' as wk_days")   
等同sql脚本   
'string' as wk_days
完成例子:
 

from peewee import JOIN, SQL, Case, fn

user.select(user.id, user.name, SQL("'string' as wk_days"))

等同sql脚本:
 

select id, name, 'string' as wk_days from user

0X04 peewee case用法

mysql脚本:

select id, name, case when id > 1000 then 'old' else 'new' end as `tag` from user

peewee:

from peewee import JOIN, SQL, Case, fn
tag = Case(None, (
                (User.id > 1000, 'old'),
            ), 'new')
query = User.select(User.id, User.name, tag.alias('tag')

0X05 peewee OR 用法

or 用法采坑
官网用法
http://docs.peewee-orm.com/en/latest/peewee/api.html#ColumnBase
or 可以用 |
比如:
where id > 500 or id < 100
peewee:
(User.id >500) | (User.id < 100)
切记加括号

 

0X06 peewee UNION 用法

官网介绍

http://docs.peewee-orm.com/en/latest/peewee/api.html#SelectQuery.union

query1 = User.select(User.name).where(User.id>100)

query2 = Author.select(Author.name).where(Author.id>100)

union = query1 | query2  

# 或者

union = query1.union_all(query2)

query = union.select_from(union.c.name)

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章