5
votes

So I had a SQLAlchemy Table with a JSON column:

from sqlalchemy.dialects.postgresql import JSON
class MyTable(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    my_json_column = db.Column(JSON)

And I tried to update the column with the dict#update method like so:

def foo(my_object, new_params):
    my_object.my_json_column.update(new_params)
    db.session.commit()

However, that didn't work. Edit: What I meant is, the updates weren't being persisted unto the database.

What did work, was this:

def foo(my_object, new_params):
    temp_params = my_object.my_json_column.copy()
    temp_params.update(new_params)
    my_object.my_json_column = new_params
    db.session.commit()

I suspect it has something to do with "immutability" or the ORM only notices changes on direct assignment, or something. Does anyone know exactly why?

1

1 Answers

10
votes

Yes. By default SQLAlchemy doesn't track changes inside dict attributes. To make it track changes, you can use the mutable extension:

class MyTable(db.Model):
    ...
    my_json_column = db.Column(MutableDict.as_mutable(JSON))