Skip to content Skip to sidebar Skip to footer

Perform A Substring Query In Peewee

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, cou

Solution 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.

Post a Comment for "Perform A Substring Query In Peewee"