Python SQLAlchemy和Postgres - 如何查询JSON元素

Dav*_*ant 24 python postgresql json sqlalchemy filter

假设我有一个Postgres数据库(9.3)并且有一个名为的表Resources.在Resources表中,我有id一个int data类型的字段,它是一个JSON类型.

假设我在表中有以下记录.

  • 1,{'firstname':'Dave','lastname':'Gallant'}
  • 2,{'firstname':'John','lastname':'Doe'}

我想要做的是编写一个查询,返回所有记录,其中数据列有一个json元素,其lastname等于"Doe"

我试着写这样的东西:

records = db_session.query(Resource).filter(Resources.data->>'lastname' == "Doe").all()
Run Code Online (Sandbox Code Playgroud)

然而,Pycharm在" - >>"上给出了编译错误

有谁知道如何编写filter子句来做我需要的东西?

Anz*_*zel 44

尝试使用astext

records = db_session.query(Resource).filter(
              Resources.data["lastname"].astext == "Doe"
          ).all()
Run Code Online (Sandbox Code Playgroud)

请注意,列必须具有JSONB类型.常规JSON列不起作用.

  • 很好的答案.此外,您提供的链接还提供了有关如何查询嵌套json的一些其他信息(例如query.filter(Resources.data [("lastname","whatever-other-nested-json-under-lastname")].astext =="Whatever Value").all()),以及如何更改数据类型. (3认同)

小智 8

您还可以显式地将字符串转换为JSON(请参阅Postgres JSON类型doc).

from sqlalchemy.dialects.postgres import JSON
from sqlalchemy.sql.expression import cast
db_session.query(Resource).filter(
    Resources.data["lastname"] == cast("Doe", JSON)
).all()
Run Code Online (Sandbox Code Playgroud)

  • 您可能需要从 dialects.postgresql 导入,而不仅仅是 postgres (2认同)
  • 您应该使用 JSONB 而不是 JSON。然后,您可以阐明更复杂的 where 子句,例如 Resources.data["size"] >cast(0.4, JSONB) (2认同)