python - peewee 各种用法

本文详细介绍了peewee ORM在Python中的应用,涵盖了子查询、混合SQL、CASE语句、OR条件以及UNION操作的使用方法,通过实例代码展示了如何在实际项目中灵活运用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)

 

 

 

您可能感兴趣的与本文相关的镜像

Python3.11

Python3.11

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值