SQLAlchemy JSON column - how to perform a contains query(SQLAlchemy JSON 列 - 如何执行包含查询)
问题描述
我在 mysql(5.7.12) 中有下表:
I have the following table in mysql(5.7.12):
class Story(db.Model):
sections_ids = Column(JSON, nullable=False, default=[])
sections_ids 基本上是一个整数列表 [1, 2, ...,n].我需要获取sections_ids包含X的所有行.我尝试了以下方法:
sections_ids is basicly a list of integers [1, 2, ...,n]. I need to get all rows where sections_ids contains X. I tried the following:
stories = session.query(Story).filter(
X in Story.sections_ids
).all()
但它抛出:
NotImplementedError: Operator 'contains' is not supported on this expression
推荐答案
使用 JSON_CONTAINS(json_doc, val[, path]):
from sqlalchemy import func
# JSON_CONTAINS returns 0 or 1, not found or found. Not sure if MySQL
# likes integer values in WHERE, added == 1 just to be safe
session.query(Story).filter(func.json_contains(Story.section_ids, X) == 1).all()
当您在顶层搜索数组时,您不需要提供路径.或者从 8.0.17 开始,您可以使用 value MEMBER OF(json_array),但在我看来,在 SQLAlchemy 中使用它不太符合人体工程学:
As you're searching an array at the top level, you do not need to give path. Alternatively beginning from 8.0.17 you can use value MEMBER OF(json_array), but using it in SQLAlchemy is a little less ergonomic in my opinion:
from sqlalchemy import literal
# self_group forces generation of parenthesis that the syntax requires
session.query(Story).filter(literal(X).bool_op('MEMBER OF')(Story.section_ids.self_group())).all()
这篇关于SQLAlchemy JSON 列 - 如何执行包含查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQLAlchemy JSON 列 - 如何执行包含查询
基础教程推荐
- 在 SQL 中连接多个表 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 无法解决整理冲突 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
