6

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 Answer 1

11

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.