I have the following flask-sqlalchemy table:
class Repo(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
followers = db.Column(db.PickleType, nullable=False)
created_on = db.Column(db.DateTime, default=datetime.utcnow)
last_modified = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
Let's say I make the following row and push it to the database:
repo = Repo(
name='My Repo',
followers=[
{'name': 'Johnny', 'id': 34752, 'views': 6},
{'name': 'Mike', 'id': 69241, 'views': 3}
]
)
db.session.add(repo)
db.session.commit()
If I want to change that row, I should be able to do the following; however, the database doesn't reflect the change.
repo.data.append({'name': 'Jessica', 'id': 12941, 'views': 12})
print(len(repo.data))
# 3
db.session.commit()
print(len(repo.data))
# 2
I've figured out the following workaround but I'd like to know why the original method doesn't work as expected.
data = list(repo.data)
data.append({'name': 'Jessica', 'id': 12941, 'views': 12})
repo.data = data
db.session.commit()
print(len(repo.data))
# 3
In order to make sqlalchemy keep track of changes of PickleType column, you need to set it to mutable=true. in your example:
followers = db.Column(db.PickleType(mutable=True), nullable=False)
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