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?
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.
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.
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With