SQLAlchemy: column_property jsonb 操作

SQLAlchemy: column_property jsonb operation

我的 Test table 有一个 JSONB 列 data:

class Test(Base):
    __tablename__ = 'test'
    data = Column(JSONB)

一个典型的文档有两个列表:

{'percentage': [10, 20, 50, 80, 90],
'age': [1.21, 2.65, 5.23, 8.65, 11.78]
}

有了 column_property 我想定制这两个列表,以便它可以作为字典使用。在 "open field" Python 中,这很简单:

dict(zip(Test.data['percentage'], Test.data['age']))

但是 column_property:

Test.data_dict = column_property(
    dict(zip(Test.data['percentage'], Test.data['age']))
)

这给出:

AttributeError: 'dict' object has no attribute 'label'

这真的可能吗?应该如何做到?

它能解决您的问题吗?

@property
def data_dict(self):
    return dict(zip(Test.data['percentage'], Test.data['age'])) 

在 PostgreSQL 中它会像这样(对于 PostgreSQL >= 9.4)

SELECT json_object(array_agg(ARRAY[p,a]))
FROM (
    SELECT unnest(ARRAY(select jsonb_array_elements_text(data->'percentage'))) p,
           unnest(ARRAY(select jsonb_array_elements_text(data->'age'))) a
    FROM test
) x;

在 SQLAlchemy 中

from sqlalchemy.orm import column_property
from sqlalchemy import select, alias, text
class Test(Base):
    __tablename__ = 'test'
    data = db.Column(JSONB)
    data_dict = column_property(
        select([text('json_object(array_agg(ARRAY[p,a]))')]).select_from(
            alias(select([
                text("unnest(ARRAY(select jsonb_array_elements_text(data->'percentage'))) p, \
                      unnest(ARRAY(select jsonb_array_elements_text(data->'age'))) a")
            ]).select_from(text('test')))
        )
    )