Sqlalchemy json column - how to preform a contains query

后端 未结 2 837
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-05 01:38

I have the following table in mysql(5.7.12):

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

section

2条回答
  •  广开言路
    2021-01-05 02:26

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

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

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题