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)

 

 

 

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