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.

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

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字段方言作为字段类型.对此有什么建议吗?

推荐答案

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相关问答推荐

SSIS Kingswaysoft Json源动态 node 名称

使用JSONata将具有相同键的字典合并

将数组中的值作为键连接到另一个数组中的值(Jolt)

使用JQ将对象数组转换为平面数组

jq - 仅在键值对存在的地方打印值

如何编写 jolt 规范以将不同的对象转换为数组

从 Inno Setup 中的 JSON 文件的每个对象中读取特定字符串

每次在 SoapUI 中发送请求时,将 JSON 响应的子 node 分配给项目变量

golang递归json来构造?

添加到数组时出错:找不到Add的重载和参数计数:1

将具有多个级别的 json 读入 DataFrame [python]

如何在linux中用jq过滤json数组?

Go - JSON 验证抛出错误,除非我在 struct 中使用指针.为什么?

SwiftUI:如何使用 0 索引数组键为 JSON 添加类型

使用 jq 同时迭代数组

在 Jersey 服务中使用 JSON 对象

将 CoffeeScript 项目转换为 JavaScript(不缩小)?

带有方法参数的 WCF webHttpBinding 错误. 最多可以在没有包装元素的情况下序列化一个主体参数

Microsoft.Net.Http 与 Microsoft.AspNet.WebApi.Client

强制 JSON.NET 在序列化 DateTime 时包含毫秒(即使 ms 组件为零)