Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flask-sqlalchemy append to pickletype doesn't update

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
like image 355
Johnny Metz Avatar asked Aug 15 '26 13:08

Johnny Metz


1 Answers

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)
like image 197
Tamir Adimor Avatar answered Aug 18 '26 02:08

Tamir Adimor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!