对JSON字段的更新不会持久保存到DB

时间:2017-03-02 15:27:27

标签: python json postgresql sqlalchemy flask-sqlalchemy

我们有一个带有JSON字段的模型,其中插入了用户标志。插入确实按预期工作,但是当删除某些标志时,它们会保留在字段中,并且更改不会持久保存到数据库。

我们的模型中有以下方法:

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

数据库是postgres,我们使用SQLalchemy JSON字段方言作为字段类型。对此有何建议?

3 个答案:

答案 0 :(得分:22)

如果您使用Postgres< 9.4您无法直接更新JSON字段。您需要 flag_modified 函数来报告对SQLAlchemy的更改:

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

答案 1 :(得分:6)

我的问题是在创建新行时引用从SQLAlchemy返回的行对象。例如这不起作用

row = db.session.query(SomeTable).filter_by(id=someId).first()
print(row.details)
newDetails = row.details
newDetails['key'] = 'new data'
row.details = newDetails
db.session.commit()

但是创建一个新的字典可行

row = db.session.query(SomeTable).filter_by(id=someId).first()
print(row.details)
newDetails = dict(row.details)
newDetails['key'] = 'new data'
row.details = newDetails
db.session.commit()

通知dict(row.details)

答案 2 :(得分:4)

我正在使用JSON字段,并且引用了以下文档。

https://docs.sqlalchemy.org/en/13/core/type_basics.html?highlight=json#sqlalchemy.types.JSON

它显示了如何使JSON-dict字段可变。 (默认是不可变的)

像这样。

const deleteData = (x) => {
    const row = x.parentNode.closest('tr');
    //delete device (error is here)
    const row = x.parentNode.closest('tr');
    devices = devices.filter(el => el !== row.getAtrribute('id'));
    console.log(devices);
document.getElementById("devices").deleteRow(x.parentElement.parentElement.rowIndex);   }

然后我可以将json字段更新为ORM。