Flask Sqlalchemy. Commit Does Not Save Changes

My commit does not save any changes to the database:

# project/models.py

from project import db
from sqlalchemy.dialects.postgresql import JSON

class Customer(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    clientid = db.Column(db.String(64))
    ...
    contextjason = db.Column(JSON)
# project/__init__.py

from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)

from project.models import Customer
custObj = Customer.query.filter(Customer.custid == custid).first()
print(custObj.contextjason)  # works fine
custObj.contextjason = { 'foo':'bar', 'so':'be it'}
db.session.commit()

The commit does not commit any changes to the DB. Actually, I don't know what it does in the background.

Can anybody tell me why I have no DB update?

Can I tell the commit somehow to log what it is doing (maybe SQL wise)?

Edit:

with SQLALCHEMY_ECHO=True

I get this for the commit:

2018-05-23 16:42:17,102 INFO sqlalchemy.engine.base.Engine COMMIT

2

1 Answer

When updating a JSON(B) attribute I think you might need to flag it as modified

from sqlalchemy.orm.attributes import flag_modified

custObj.contextjason = { 'foo':'bar', 'so':'be it'}
flag_modified(custObj, "contextjason")
db.session.commit()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest