简体   繁体   English

如何在Peewee的SelectQuery中实现表达式的数组切片?

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

Is it possible to implement array slicing for Expression within SelectQuery in peewee? 是否可以在peewee的SelectQuery中实现表达式的数组切片?

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']" . 我想在带有regexp的PostgreSQL查询中使用模式匹配,并且可以通过fn.REGEXP_MATCH(col_name, regexp)来做到这fn.REGEXP_MATCH(col_name, regexp)但它会以字符串形式返回数组,例如"['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] . 因此,我只需要像这样在DB端获取带有slice的array的第一个元素: (regexp_match(col_name, regexp)[1]

I need to implement this query with orm: 我需要使用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. 我唯一想到的就是不使用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). 您可以尝试使用“ unnest”功能(通过fn.unnest)。

If you're looking for implementing array-type stuff, check out the implementation of ArrayField in playhouse/postgres_ext.py: 如果您正在寻找实现数组类型的东西,请在playhouse / postgres_ext.py中检查ArrayField的实现:

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

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

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