Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

python - In SQLAlchemy, how does the dict update method interact with the ORM?

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)

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

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. Does anyone know exactly why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...