Вопрос

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)

Example rows in this table:

id: 1, items: [2,3,5]
id: 2, items: [2,3,5, 8, 12]
id: 3, items: [2,5]
id: 4, items: []

Expected result:

1 3
2 5
3 2
4 0

Is there something like this:

session.query(Post.id, len(Post.items))

Note: The JSON field contains an array of complex objects, I have used integers here only for the purpose of illustration.

Это было полезно?

Решение

Found a solution

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)

and use it like this

session.query(Post.id, json_array_length(Post.items))

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

Другие советы

A simpler solution, using the sqlalchemy.sql.expression.func object:

session.query(Post.id, func.json_array_length(Post.items))

From the documentation:

func is a special object instance which generates SQL functions based on name-based attributes

...

Any name can be given to func. If the function name is unknown to SQLAlchemy, it will be rendered exactly as is.

Source: http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.func

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top