Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 838
cozos Avatar asked Mar 30 '16 01:03

cozos


People also ask

How does SQLAlchemy update data?

Update table elements in SQLAlchemy. Get the books to table from the Metadata object initialized while connecting to the database. Pass the update query to the execute() function and get all the results using fetchall() function. Use a for loop to iterate through the results.

How does the querying work with SQLAlchemy?

All SELECT statements generated by SQLAlchemy ORM are constructed by Query object. It provides a generative interface, hence successive calls return a new Query object, a copy of the former with additional criteria and options associated with it.

Should I use SQLAlchemy core or ORM?

If you want to view your data in a more schema-centric view (as used in SQL), use Core. If you have data for which business objects are not needed, use Core. If you view your data as business objects, use ORM. If you are building a quick prototype, use ORM.

Is SQLAlchemy an ORM?

SQLAlchemy is a library that facilitates the communication between Python programs and databases. Most of the times, this library is used as an Object Relational Mapper (ORM) tool that translates Python classes to tables on relational databases and automatically converts function calls to SQL statements.


1 Answers

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))
like image 157
univerio Avatar answered Sep 23 '22 22:09

univerio