SQLAlchemy:如何对列值执行regexp_replace
我想用SQLAlchemy实现类似于
cast(regexp_replace(entry.page_title,'.*::: ','') AS INT)
的功能。
我看到可以使用混合属性在ORM映射的类上执行一些函数。我尝试了以下方法,但我不太明白如何用混合属性来进行字符串替换。
class Entry(object):
def __init__(self, page_title):
self.page_title = page_title
@hybrid_property
def original_brand_id(self):
return self.page_title.partition(' ::: ')[-1]
###OR ALSO TRIED DOING:
return re.sub(r'[.*::: ]','',self.page_title)
我知道问题在于我想把Entry的page_title当作一个string
来处理,但实际上它是一个InstrumentedAttribute
。不过我不太清楚怎么才能获取到字符串的值,以便实现我想要的功能。
这真的可能吗?
1 个回答
7
原来有一个函数可以做到这一点,所以我可以这样做:
@hybrid_property
def original_brand_id(self):
return cast(func.regexp_replace(self.page_title, '.*::: ',''), Numeric)
我本来想删掉这个问题的,但我花了很长时间在谷歌上搜索才找到这个答案,所以我决定把它留在这里,以防其他人也需要。