在SQLAlchemy中,dict update方法是如何与ORM交互的? [英] In SQLAlchemy, how does the dict update method interact with the ORM?

查看:17
本文介绍了在SQLAlchemy中,dict update方法是如何与ORM交互的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个带有 JSON 列的 SQLAlchemy 表:

So I had a SQLAlchemy Table with a JSON column:

from sqlalchemy.dialects.postgresql import JSON
class MyTable(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    my_json_column = db.Column(JSON)

我尝试使用 dict#update 方法更新列,如下所示:

And I tried to update the column with the dict#update method like so:

def foo(my_object, new_params):
    my_object.my_json_column.update(new_params)
    db.session.commit()

然而,这没有用.我的意思是,更新没有被持久化到数据库中.

什么起作用了,是这样的:

What did work, was this:

def foo(my_object, new_params):
    temp_params = my_object.my_json_column.copy()
    temp_params.update(new_params)
    my_object.my_json_column = new_params
    db.session.commit()

我怀疑它与不变性"有关,或者 ORM 只注意到直接分配的变化,或者其他什么.有谁知道确切原因吗?

I suspect it has something to do with "immutability" or the ORM only notices changes on direct assignment, or something. Does anyone know exactly why?

推荐答案

是的.默认情况下,SQLAlchemy 不跟踪 inside dict 属性的变化.要使其跟踪更改,您可以使用 mutable 扩展名:

Yes. By default SQLAlchemy doesn't track changes inside dict attributes. To make it track changes, you can use the mutable extension:

class MyTable(db.Model):
    ...
    my_json_column = db.Column(MutableDict.as_mutable(JSON))

这篇关于在SQLAlchemy中,dict update方法是如何与ORM交互的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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