【问题标题】:order_by Levenshtein Distance in SqlAlchemySqlAlchemy 中的 order_by Levenshtein 距离
【发布时间】:2021-03-05 01:50:05
【问题描述】:

我想在用于搜索的端点返回的一组(小)行上排序_by Levenshtein distance。我的设置:

  • sqlalchemy=='1.3.19'
  • Postgres 引擎 11.3

我最初使用Model

class Model(Base):
    id = Column(...)
    name = Column(...)


class Child(Column):
    id = Column(...)
    model_id = Column(...)
    model = relationship("Model", backref='children', ...)


class Child2(Column):
    id = Column(...)
    model_id = Column(...)
    model = relationship("Model", backref='child2s', ...)


db: Session = get_session()
q = (
    db.query(Model)
    .options(joinedload(Model.child2s), joinedload(Model.children))
    .filter(Model.children.has(id=12345))
    .order_by(text("LEVENSHTEIN(model.name, 'SomeString')")) <<< this is what caused an error
)

res = q.all()

这是错误:

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) missing FROM-clause entry for table "model"

这失败了,因为joinedload 选项为我的模型引入了一个别名,因此model.name 现在被命名为anon_1_model_name。因为order_by 是我根据传入请求的参数应用于查询的连接/过滤操作列表之一,所以model 表的别名在运行时是未知的。有没有使用 Postgres Levenshtein 函数进行排序的好方法?

【问题讨论】:

    标签: python postgresql sqlalchemy


    【解决方案1】:

    和往常一样,SqlAlchemy 超出了我的预期。正确的语法是:

    q = (
        db.query(Model)
        .options(joinedload(Model.child2s), joinedload(Model.children))
        .filter(Model.children.has(id=12345))
        .order_by(func.levenshtein(Model.name, 'SomeString'))
    )
    

    【讨论】:

    • 嗨! func.levenshtein 的导入是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 2014-08-04
    相关资源
    最近更新 更多