加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

postgresql – SqlAlchemy:查询具有数组的长度为json的字段

发布时间:2020-12-13 16:02:29 所属栏目:百科 来源:网络整理
导读:我有一个表格,其中包含 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
我有一个表格,其中包含 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读