简体   繁体   中英

How to implement array slicing for Expression within SelectQuery in peewee?

Is it possible to implement array slicing for Expression within SelectQuery in peewee?

I want to use pattern matching in PostgreSQL query with regexp, and I can do it with fn.REGEXP_MATCH(col_name, regexp) but it returns array as string like so "['foo']" . So I need to get only first element of array with slice on the DB side like so: (regexp_match(col_name, regexp)[1] .

I need to implement this query with orm:

SELECT (regexp_match(h.name, '^ATM-\w{5}-(\S+)$'))[1] FROM zbxhost h;

And this try returns me array as string:

ZbxHost.select(ZbxHost.name, fn.REGEXP_MATCH(ZbxHost.name, '^ATM-\w{5}-(\S+)$'))

The only thing that comes to my mind is not to use regexp. And in this case it's possible, but what if it will be necessary in future?

You might try using the "unnest" function (via fn.unnest).

If you're looking for implementing array-type stuff, check out the implementation of ArrayField in playhouse/postgres_ext.py:

https://github.com/coleifer/peewee/blob/b48aab31fe5cd788099b821b2c2cf5d05d196d3f/playhouse/postgres_ext.py#L114-L184

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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