简体   繁体   English

在SQLAlchemy中,dict更新方法如何与ORM交互?

[英]In SQLAlchemy, how does the dict update method interact with the ORM?

So I had a SQLAlchemy Table with a JSON column: 所以我有一个带有JSON列的SQLAlchemy表:

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

And I tried to update the column with the dict#update method like so: 我试图用dict#update方法更新列,如下所示:

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

However, that didn't work. 但是,那没有用。 Edit: What I meant is, the updates weren't being persisted unto the database. 编辑: 我的意思是,更新没有持久保存到数据库中。

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

I suspect it has something to do with "immutability" or the ORM only notices changes on direct assignment, or something. 我怀疑这与“不变性”有关,或者ORM仅注意到直接分配的更改或其他原因。 Does anyone know exactly why? 有谁知道为什么吗?

Yes. 是。 By default SQLAlchemy doesn't track changes inside dict attributes. 默认情况下,SQLAlchemy不跟踪dict属性内部的更改。 To make it track changes, you can use the mutable extension: 要使其跟踪更改,可以使用mutable扩展名:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM