SqlAlchemy:查询具有数组的长度json字段 [英] SqlAlchemy: Querying the length json field having an array
问题描述
我有一个表,其中的字段类型为JSON.JSON字段包含带有数组的JSON对象.如何查询每一行的数组长度?
I have a table with a field of type JSON. The JSON field contains a JSON object with an array. How do I query the length of this array for each row?
class Post(Base):
__tablename__ = 'posts'
id = Column(Integer, primary_key=True)
items = Column(JSON)
此表中的示例行:
id: 1, items: [2,3,5]
id: 2, items: [2,3,5, 8, 12]
id: 3, items: [2,5]
id: 4, items: []
预期结果:
1 3
2 5
3 2
4 0
有这样的东西吗?
session.query(Post.id, len(Post.items))
注意:JSON字段包含一组复杂的对象,在这里我仅将整数用于说明目的.
推荐答案
找到了解决方案
创建一个像这样扩展FunctionElement的类
Create a class that extends FunctionElement like this
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".如果您要为其他数据库使用此功能,则需要更改其功能.请参考 http://docs.sqlalchemy.org/zh/rel_0_9/core/compiler.html#further-examples
Note: this will work on postgres because the function 'json_array_length' is defined in it. If you want this for a different DB that function will need to change. Refer http://docs.sqlalchemy.org/en/rel_0_9/core/compiler.html#further-examples
这篇关于SqlAlchemy:查询具有数组的长度json字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!