python - SQLAlchemy:按 JSON 列中的键过滤

标签 python postgresql sqlalchemy

SQLAlchemy 版本:1.2.10,PostgreSQL 版本:10-something。
我正在关注 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'})]

接下来我要做的是根据我的 JSON 列中特定键下的值查询行,在 this 之后示例:

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) 没有属性文本。这是否意味着文档有误?

最佳答案

您正在使用 sqlalchemy.types.JSON没有 astext。使用 sqlalchemy.dialects.postgresql.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)
)

关于python - SQLAlchemy:按 JSON 列中的键过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53195944/

相关文章:

python - 我应该总是使用 'implicit_returning' :False in SQLAlchemy?

python - 使用 SQLAlchemy、to_sql 使用 pandas 写入 MySQL 数据库

python - 如何在 IronWorker 中捆绑 Python 依赖项?

python - celery 4.0.0 : No such transport: django

python - 如何在 NumPy 中构建三线性插值的查找表?

sql - 在 PostgreSQL 上插入或更新之前检查给定值的触发器

postgresql - 如何检查数字是否为 NaN

php - INSERT 如果不存在,否则返回 id

python - 使用 fastapi-contrib 的 FastApi 分页错误

python - 从一个 Flask View 重定向到另一个 Flask View