SQLALchemy-Utils:在 LTree 中使用“~”运算符

Soh*_*oqi 5 sqlalchemy flask flask-sqlalchemy

我正在尝试使用 Flask、SQLAlchemy-Utils和 Flask-SQLAlchemy查询 Postgres 物化路径视图(ltree)。SQLAlchemy-Util Docs展示了使用 LTree 的 '==', '!=' 运算符的用法。如何使用“~”运算符?

我在 sqlalchemy_utils/ltree.py 中看到了代码:

class comparator_factory(types.Concatenable.Comparator):
    def ancestor_of(self, other):
        if isinstance(other, list):
            return self.op('@>')(expression.cast(other, ARRAY(LtreeType)))
        else:
            return self.op('@>')(other)

    def descendant_of(self, other):
        if isinstance(other, list):
            return self.op('<@')(expression.cast(other, ARRAY(LtreeType)))
        else:
            return self.op('<@')(other)

    def lquery(self, other):
        if isinstance(other, list):
            return self.op('?')(expression.cast(other, ARRAY(LQUERY)))
        else:
            return self.op('~')(other)

    def ltxtquery(self, other):
        return self.op('@')(other)
Run Code Online (Sandbox Code Playgroud)

这是 LtreeType 的子类。

简单来说==,我正在使用:

Model.query.filter(Model.path == LTree('1.2')).all()
Run Code Online (Sandbox Code Playgroud)

但是使用此表达式会引发验证错误:

Model.query.filter(Model.path == LTree('~1.2')).all()
Run Code Online (Sandbox Code Playgroud)

如何在有效的 SQLALchemy 查询中格式化上述表达式?

Soh*_*oqi 5

我能够用这段代码解决这个问题。

礼貌 Github 问题:SQLAlchemy-Util 问题 (253)

 from sqlalchemy.sql import expression
 from sqlalchemy_utils.types.ltree import LQUERY

 custom_lquery = '*.some.pattern'
 Model.query.filter(Model.path.lquery(expression.cast(custom_lquery, LQUERY))).all()
Run Code Online (Sandbox Code Playgroud)