【发布时间】: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