我有一个表格,其中包含
JSON类型的字段.
JSON字段包含带有数组的JSON对象.如何查询每行的数组长度?
class Post(Base): __tablename__ = 'posts' id = Column(Integer,primary_key=True) items = Column(JSON)
此表中的示例行:
id: 1,items: [2,3,5] id: 2,5,8,12] id: 3,5] id: 4,items: []
预期结果:
1 3 2 5 3 2 4 0
有这样的事情:
session.query(Post.id,len(Post.items))
注意:JSON字段包含复杂对象的数组,我在这里仅使用整数来说明.
解决方法
找到了解决方案
创建一个像这样扩展FunctionElement的类
from sqlalchemy.sql.expression import FunctionElement from sqlalchemy.ext.compiler import compiles class json_array_length(FunctionElement): name = 'json_array_len' @compiles(json_array_length) def compile(element,compiler,**kw): return "json_array_length(%s)" % compiler.process(element.clauses)
并像这样使用它
session.query(Post.id,json_array_length(Post.items))
注意:这将适用于postgres,因为函数’json_array_length’在其中定义.如果您希望将此功能用于需要更改功能的其他DB.
参见http://docs.sqlalchemy.org/en/rel_0_9/core/compiler.html#further-examples
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。