Just assigning a value and executing it will work for all data types, but with the JSON and Pickled attributes. Since the pickled type is explained above, I will stop a slightly different but simple way to update JSON.
class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), unique=True) data = db.Column(db.JSON) def __init__(self, name, data): self.name = name self.data = data
Let's say the model is similar to the above.
user = User("Jon Dove", {"country":"Sri Lanka"}) db.session.add(user) db.session.flush() db.session.commit()
This will add the user to the MySQL database with the data {"country": "Sri Lanka"}
Data changes will be ignored. My code that did not work is as follows.
user = User.query().filter(User.name=='Jon Dove') data = user.data data["province"] = "south" user.data = data db.session.merge(user) db.session.flush() db.session.commit()
Instead of going through the hard work of copying JSON into a new dict (without assigning it to a new variable as above), which should have worked, I found an easy way to do this. There is a way to mark a system that has changed JSON.
Below is the working code.
from sqlalchemy.orm.attributes import flag_modified user = User.query().filter(User.name=='Jon Dove') data = user.data data["province"] = "south" user.data = data flag_modified(user, "data") db.session.merge(user) db.session.flush() db.session.commit()
It worked like a charm. There is another method suggested along with this method here. I hope I helped someone.
Hareendra Chamara Philips Nov 25 '17 at 0:31 2017-11-25 00:31
source share