SQLAlchemy JSON列-如何执行包含查询


问题内容

我在mysql(5.7.12)中有下表:

class Story(db.Model):
    sections_ids = Column(JSON, nullable=False, default=[])

sections_ids 是basicly整数[1,2,…,N]的列表。我需要获取sections_ids包含X的所有行。我尝试了以下操作:

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()

在顶层搜索数组时,无需指定 path