简体   繁体   English

如何在 SQLAlchemy(特别是 Flask-SQLAlchemy)中使用 PostgreSQL 扩展?

[英]How to use PostgreSQL extensions in SQLAlchemy (specifically Flask-SQLAlchemy)?

In the website I'm making with Flask, I'm trying to "upgrade" my search bar by using the pg_trgm PostgreSQL extension to match words even after being spelled wrong.在我使用 Flask 制作的网站中,我试图通过使用 pg_trgm PostgreSQL 扩展来“升级”我的搜索栏,以匹配单词,即使拼写错误也是如此。 However, I'm having trouble figuring out how to use the extension's custom functions alongside SQLAlchemy.但是,我无法弄清楚如何将扩展的自定义功能与 SQLAlchemy 一起使用。

Will I have to use raw SQL to properly perform the queries, or is there a way to do this more cleanly?我是否必须使用原始 SQL 来正确执行查询,或者有没有办法更干净地做到这一点?

Assuming the extension is configured correctly, these functions should be accessible like any other database function.假设扩展配置正确,这些功能应该可以像任何其他数据库 function 一样访问。 For example, here's how the similarity function might be called using SQLAlchemy core:例如,以下是使用 SQLAlchemy 内核调用similarity function 的方式:

import sqlalchemy as sa

engine = sa.create_engine('postgresql+psycopg2:///test', echo=True, future=True)

metadata = sa.MetaData()

tbl = sa.Table('t70546926', metadata,
               sa.Column('c1', sa.String, primary_key=True),
               sa.Column('c2', sa.String))
tbl.drop(engine, checkfirst=True)
tbl.create(engine)

ins = sa.insert(tbl).values(c1='Alice', c2='Alison')

with engine.begin() as conn:
    conn.execute(ins)

query = sa.select(sa.func.similarity(tbl.c.c1, tbl.c.c2).label('similarity_result'))
with engine.connect() as conn:
    rows = conn.execute(query)
    for row in rows:
        print(row.similarity_result)

For Flask-SQLAlchemy, you might do something like this:对于 Flask-SQLAlchemy,你可以这样做:

result = dbsession.query(sa.func.similarity(val1, val2)).all()

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

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