SQLAlchemy + PostgreSQL + PG 正则表达式 [英] SQLAlchemy + PostgreSQL + PG regex

查看:39
本文介绍了SQLAlchemy + PostgreSQL + PG 正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SA 支持正则表达式,但那些似乎是 Python 正则表达式(SQLalchemy 查询中的正则表达式?)

SA has support for regexes but those seem to be Python regexps (Regular expressions in SQLalchemy queries?)

我需要在匹配某些行时使用正则表达式(一行包含 1 个日志行,因此正则表达式是自然匹配)但出于性能原因,我更愿意使用 PG 后端来执行此操作,例如 这个问题:

I need to use regex on matching some rows (a row contains 1 log line, so regex is a natural match) but for performance reasons I would prefer to do it using PG backend, like in this question:

select * from table where name ~ 'foo';

如何在一个查询中结合使用 PG 实现的正则表达式和 SQLAlchemy 对象选择?

How can I combine both PG-implemented regex AND SQLAlchemy object selection in one query?

推荐答案

filter() Query 对象的方法允许您使用原始 SQL 作为过滤器.所以,你可以做...

The filter() method of the Query object allows for you to use raw SQL for the filter. So, you could do...

Table.query.filter("name ~ 'foo'")

请注意,如果您想将此作为参数提供,您可以使用 text()params()...

Note that if you want to provide this as an argument, you can use text() and params()...

from sqlalchemy.sql import text

Table.query.filter(text('name ~ :reg')).params(reg='foo')

因为我们使用 text() 在过滤器中定义了reg"绑定参数,所以我们需要确保我们定义了值,我们可以使用 params()代码>.

Because we define the "reg" bind parameter in the filter using text(), we need to make sure we define the value, which we can do using params().

这篇关于SQLAlchemy + PostgreSQL + PG 正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆