对 JSON 字段的更新不会持续到 DB [英] Updates to JSON field don't persist to DB

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

问题描述

我们有一个带有 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

数据库是 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 字段的更新不会持续到 DB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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