简体   繁体   English

在Peewee中执行子字符串查询

[英]Perform a substring query in Peewee

I'm using Python 2.7 together with Peewee. 我和Peewee一起使用Python 2.7。 At this moment, I need to use Peewee to execute the following SQL query: 此时,我需要使用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

My first problem here is how to perform a substring with Peewee. 我的第一个问题是如何使用Peewee执行子串。 I have searched the documentation and, so far, no lucky. 我搜索了文档,到目前为止,没有幸运。

So, the basic question is: How do I perform a substring SQL function using Peewee? 所以,基本问题是: 如何使用Peewee执行substring SQL函数? It would also be very nice if someone can give me some directions of how to perform the entire query above with Peewee. 如果有人可以给我一些关于如何使用Peewee执行上述整个查询的指示,那也是非常好的。

Ok. 好。

After searching and searching, I finally found it. 经过搜索和搜索,我终于找到了它。 It can be done by simply using fn.substr . 它可以通过简单地使用fn.substr来完成。

A reference to the function can be found here . 可在此处找到对该功能的引用。 Strangely, a documentation of this same function is not present in the fn documentation page (only the method over is documented there). 奇怪的是,该相同功能的一个文档中不存在的fn文档页面 (仅该方法over被记录在那里)。

To answer my own question, the SQL query is going to be something like (not tested): 要回答我自己的问题,SQL查询将会像(未经过测试):

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))

Hope this can help someone in the future. 希望这可以帮助将来的某个人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM