2

I have a table Movies with a JSON column, defined as:

movie_info = Column('movie_info', JsonEncodedDict)

Where JsonEncodedDict:

class JsonEncodedDict(TypeDecorator):
    impl = Text

    def process_bind_param(self, value, dialect):
        if value is None:
            return '{}'
        else:
            return json.dumps(value)

    def process_result_value(self, value, dialect):
        if value is None:
            return {}
        else:
            return json.loads(value)

Inserting works as expected. My problem starts when I want to query data and perform filtering on my column. Suppose I have a record, in which movie_info column is:

{
    "title": "The Movie - 3",
    "review": "Best movie I have ever seen"
}

I would like to query my table and get all records where review contains 'best'

I have tried things like

session.query(Movies).filter('best' in Movies.movie_info['review']).all()

session.query(Movie).filter('best' in func.json_compare(Movies.movie_info['review'])).all()

and several more queries but nothing works. Any idea would be appreciated

1
  • Why use a TypeDecorator at all, if your MySQL back-end is using its native JSON type? Your updates to this field will be faithfully applied in the ORM, and you only need to flag a record change using sqlalchemy.orm.attributes.flag_modified prior to a commit(). Commented Aug 22, 2022 at 21:10

1 Answer 1

7

That was quick but I found a solution. I'm not deleting this question, as I've yet to find any answer online so I believe this will be helpful to others.

Using json_extract instead of json_contains:

session.query(Movies).filter(func.json_extract(Movies.movie_info, '$.review').ilike('%best%')).all()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.