Python 在Peewee中执行子字符串查询
我正在使用Python2.7和Peewee。此时,我需要使用Peewee执行以下SQL查询:Python 在Peewee中执行子字符串查询,python,sql,peewee,Python,Sql,Peewee,我正在使用Python2.7和Peewee。此时,我需要使用Peewee执行以下SQL查询: select a, b, substring(c, 1, 3) as alias1, count(substring(c, 1, 3)) as alias2 from Table where <some where condition, not relevant here> group by a, alias1 选择 A. B 子字符串(c,1,3)作为
select
a,
b,
substring(c, 1, 3) as alias1,
count(substring(c, 1, 3)) as alias2
from Table
where <some where condition, not relevant here>
group by a, alias1
选择
A.
B
子字符串(c,1,3)作为别名1,
将(子字符串(c,1,3))计数为别名2
从桌子上
哪里
按a分组,别名1
这里我的第一个问题是如何使用Peewee执行子字符串。我已经搜索了文档,到目前为止,还没有找到幸运儿
因此,基本问题是:如何使用Peewee执行子字符串SQL函数?
如果有人能告诉我如何使用Peewee执行上面的整个查询,那将非常好。好的
我找了又找,终于找到了。只需使用fn.substr
即可完成
可以找到对该函数的引用。奇怪的是,中没有相同函数的文档(这里只记录了方法over
)
为了回答我自己的问题,SQL查询将类似(未测试):
TableModel.select(
A.
B
fn.substr(c,1,3).别名('alias1'),
fn.count(fn.substr(c,1,3)).alias('alias2')
) \
.where()\
(a,fn.substr(c,1,3))
希望这能对将来的人有所帮助。peewee fn对象很神奇。您可以使用它调用任何SQL函数,它是生成SQL函数调用的语法糖。因此,您可以执行
fn.STRFTIME(…,…)
甚至嵌套fn
调用。谢谢@coleifer:)。现在不确定我是否误解了文档,或者文档是否没有明确说明。
TableModel.select(
a,
b,
fn.substr(c, 1, 3).alias('alias1'),
fn.count(fn.substr(c, 1, 3)).alias('alias2')
) \
.where(<some where condition, not relevant here>) \
.group_by(a, fn.substr(c, 1, 3))