繁体   English   中英

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

[英]Python SQLAlchemy and Postgres - How to query a JSON element

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

假设我在上述表格中有以下记录。

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

我想做的是编写一个查询,该查询将返回所有记录,其中数据列具有一个json元素,其姓氏等于“ Doe”

我试图写这样的东西:

records = db_session.query(Resource).filter(Resources.data->>'lastname' == "Doe").all()

Pycharm给了我“->>”的编译错误

有谁知道我会怎么写filter子句来做我所需要的?

尝试使用astext

records = db_session.query(Resource).filter(
              Resources.data["lastname"].astext == "Doe"
          ).all()

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

您也可以将字符串显式转换为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()

根据sqlalchemy.types.JSON ,您可以这样做

from sqlalchemy import JSON
from sqlalchemy import cast
records = db_session.query(Resource).filter(Resources.data["lastname"] == cast("Doe", JSON)).all()

如果您使用的是JSON类型(而非JSONB),则以下内容对我有用:

注意'"object"'

    query = db.session.query(ProductSchema).filter(
        cast(ProductSchema.ProductJSON["type"], db.String) != '"object"'
    )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM