我想在用于搜索的端点返回的一组(小(行上按Levenstein距离排序。我的设置:
- 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-Levenstein函数进行排序的好方法?
和往常一样,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'))
)