JSON字段的更新不会持久保存到数据库 [英] Updates to JSON field don't persist to DB

查看:361
本文介绍了JSON字段的更新不会持久保存到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

databasse是postgres,我们将SQLalchemy JSON字段方言用作字段类型.有什么建议吗?

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

推荐答案

如果您使用的是Postgres< 9.4您不能直接更新JSON字段.您需要 flag_modified 函数将更改报告给SQLAlchemy:

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

这篇关于JSON字段的更新不会持久保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆