Perform a substring query in Peewee

若如初见. 提交于 2019-12-11 10:48:10

问题


I'm using Python 2.7 together with Peewee. At this moment, I need to use Peewee to execute the following SQL query:

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. 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? It would also be very nice if someone can give me some directions of how to perform the entire query above with Peewee.


回答1:


Ok.

After searching and searching, I finally found it. It can be done by simply using 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).

To answer my own question, the SQL query is going to be something like (not tested):

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.



来源:https://stackoverflow.com/questions/35501683/perform-a-substring-query-in-peewee

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!