首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQLALchemy:在LTree中使用'~‘操作符

SQLALchemy:在LTree中使用'~‘操作符
EN

Stack Overflow用户
提问于 2016-10-19 17:11:48
回答 1查看 1.3K关注 0票数 5

我试图查询Postgres物化路径视图(Ltree),使用Flask、SQLAlchemy和Flask。SQLAlchemy文档显示了使用LTree的'==‘、'!=’操作符的用法。我如何使用“~”操作符?

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

代码语言:javascript
复制
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)

这是LtreeType的子类。

对于一个简单的==,我使用:

代码语言:javascript
复制
Model.query.filter(Model.path == LTree('1.2')).all()

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

代码语言:javascript
复制
Model.query.filter(Model.path == LTree('~1.2')).all()

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-15 07:45:02

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

礼节-问题:SQLAlchemy-Util问题(253)

代码语言:javascript
复制
 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()
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40137655

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档