Updates to JSON field don't persist to DB

trnc picture trnc · Mar 2, 2017 · Viewed 9.5k times · Source

We have a model with a JSON field where user flags get inserted. Inserting does work as expected, but when removing certain flags, they stay in the field and changes don't get persisted to the DB.

We have the following method in our model:

def del_flag(self, key):
    if self.user_flags is None or not key in self.user_flags:
        return False
    else:
        del self.user_flags[key]
        db.session.commit()        
        return True

The databasse is postgres and we use the SQLalchemy JSON field dialect for the field type. Any advice on this?

Answer

José Vte. Calderón picture José Vte. Calderón · Aug 25, 2017

If you are using Postgres < 9.4 you can't update JSON field directly. You need flag_modified function to report the change to SQLAlchemy:

from sqlalchemy.orm.attributes import flag_modified
model.data['key'] = 'New value'
flag_modified(model, "data")
session.add(model)
session.commit()