【问题标题】:SQLAlchemy: Query a JSON column (PostgreSQL) containing array and counting matchesSQLAlchemy:查询包含数组和计数匹配的 JSON 列 (PostgreSQL)
【发布时间】:2021-08-07 12:26:22
【问题描述】:

我对 SQLAlchemy 有点陌生,并且在 db 中使用 JSON 列。

我的数据库模型

from sqlalchemy.dialects.postgresql import JSON
    
class Traydetails(db.Model):
    
    id= db.Column(db.Integer, autoincrement=True, primary_key=True)
    traynumber = db.Column(db.String, unique=True)
    safety_data = db.Column(JSON)

我的 JSON 结构

[{"Formulation": "Form1", "Hazard Rating": "Class B"}, {"Formulation": "Form2", "Hazard Rating": "Class B"}, {"Formulation": "Form3", "Hazard Rating": "Class B"}, {"Formulation": "Form4", "Hazard Rating": "Class B"}, {"Formulation": "Form5", "Hazard Rating": "Class B"}, {"Formulation": "Form6", "Hazard Rating": "Class B"}, {"Formulation": "Form7", "Hazard Rating": "Class B"}, {"Formulation": "Form8", "Hazard Rating": "Class B"}, {"Formulation": "Form9", "Hazard Rating": "Class B"}, {"Formulation": "Form10", "Hazard Rating": "Class B"}]

试过查询1

hazard = Traydetails.query.filter(Traydetails.safety_data['Hazard Rating'].astext == "Class B").count()

它什么也不返回。

试过查询2

hazard = Traydetails.query.filter(Traydetails.safety_data[0]['Hazard Rating'].astext.cast(Unicode) == "Class B").count()

它只返回一个(因为我是在比较一个位置)

但我的目标是计算危险等级(关键)中有多少 B 级。 请注意,会有不同类型的类,例如 Class A 、 Class B 、 Class N。

【问题讨论】:

    标签: python json postgresql sqlalchemy


    【解决方案1】:

    您可以使用 postgres 函数 json_array_elements 形成一个子查询,您可以过滤该子查询以检索 Class B 危险等级的计数:

    from sqlalchemy import func
    subq = session.query(func.json_array_elements(Traydetails.safety_data).label('safety_data')).subquery()
    
    count = session.query(subq).filter(subq.c.safety_data.op('->>')('Hazard Rating') == 'Class B').count()
    print(count)
    

    filter 正在使用子查询的安全数据标记列:subq.c.safety_data。对于.op,我们使用自定义运算符->>,它将json 转换为文本。有关运营商的更多信息,请参阅the docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-21
      • 2016-12-05
      • 2017-10-28
      • 1970-01-01
      相关资源
      最近更新 更多