在SQLAlchemy中,dict更新方法如何与ORM交互? [英] In SQLAlchemy, how does the dict update method interact with the ORM?
本文介绍了在SQLAlchemy中,dict更新方法如何与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()
但是,那没有用.我的意思是,更新没有持久保存到数据库中.
起作用了,是这样的:
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不会跟踪内部 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更新方法如何与ORM交互?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文