0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SQLAlchemyでmysqlのjson_containsを使うのに文字列で検索する方法

Posted at

json_contains使って文字列で検索しようとしたら少しハマった。

成功例

""で囲む必要がある。実際mysqlで直接selectするときもjson_contains(fuga, '"piyo"')とする必要がある。

success.py
from sqlalchemy import func

search_str = 'piyo'
db.session.query(Hoge).filter(func.json_contains(Hoge.fuga, f'"{search_str}"'))

失敗コード例

fail.py
from sqlalchemy import func

search_str = 'piyo'
db.session.query(Hoge).filter(func.json_contains(Hoge.fuga, search_str))

エラーメッセージ

sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (3141, 'Invalid JSON text in argument 2 to function json_contains: "Invalid value." at position 0.')
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?