SQLAlchemy:按JSON列中的键进行过滤

时间:2018-11-07 18:52:30

标签: python postgresql sqlalchemy

SQLAlchemy版本:1.2.10,PostgreSQL版本:10左右。
我正在跟踪here

中的文档示例
In [1]: import sqlalchemy as sa

In [2]: from nimble_core.backend.persistence.pg import PG_META_DATA

In [3]: data_table = sa.Table('data_table', PG_META_DATA,
   ...:     sa.Column('id', sa.Integer, primary_key=True),
   ...:     sa.Column('data', sa.JSON)
   ...: )

In [4]: data_table.create()

In [5]: with PG_ENGINE.connect() as conn:
   ...:     conn.execute(
   ...:         data_table.insert(),
   ...:         data = {"key1": "value1", "key2": "value2"}
   ...:     )
   ...:

位置:

In [10]: PG_ENGINE
Out[10]: Engine(postgresql://nimble:***@localhost:5432/nimble)

In [11]: PG_META_DATA
Out[11]: MetaData(bind=Engine(postgresql://nimble:***@localhost:5432/nimble))

In [12]: PG_META_DATA.sorted_tables
Out[12]:
[Table('data_table', MetaData(bind=Engine(postgresql://nimble:***@localhost:5432/nimble)), Column('id', Integer(), table=<data_table>, primary_key=True, nullable=False), Column('data', JSON(), table=<data_table>), schema=None)]

插入操作后,表只有一行:

    In [14]: PG_ENGINE.execute(sa.select([data_table])).fetchall()
    Out[14]: [(1, {u'key2': u'value2', u'key1': u'value1'})]

我接下来要做的是按照this示例,通过JSON列中特定键下的值查询行:

In [17]: PG_ENGINE.execute(
    ...:     sa.select([data_table]).where(
    ...:         data_table.c.data['key1'].astext == 'value1'
    ...:     )
    ...: )
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-17-3c4db8afed3f> in <module>()
      1 PG_ENGINE.execute(
      2     sa.select([data_table]).where(
----> 3         data_table.c.data['key1'].astext == 'value1'
      4     )
      5 )

/Users/psih/Work/nimble-server/runtime/lib/python2.7/site-packages/sqlalchemy/sql/elements.pyc in __getattr__(self, key)
    686                     type(self).__name__,
    687                     type(self.comparator).__name__,
--> 688                     key)
    689             )
    690

AttributeError: Neither 'BinaryExpression' object nor 'Comparator' object has an attribute 'astext'

很显然,data_table.c.data['key1']的类型是(sqlalchemy.sql.elements.BinaryExpression),没有属性astext。这是否意味着文档有误?

2 个答案:

答案 0 :(得分:2)

您正在使用没有astext的{​​{3}}。请改用sqlalchemy.types.JSON

import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

data_table = sa.Table('data_table', PG_META_DATA,
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('data', postgresql.JSON)
)

答案 1 :(得分:0)

您可以在sqlalchemy过滤器中使用原始sql

from sqlalchemy import text

db.session.query(DataTable).filter(text("data->['key1'] = 'value1'")