6

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

Anson VanDoren
  • 956
  • 1
  • 12
  • 22
caliph
  • 1,389
  • 3
  • 27
  • 52
  • 1
    SQLAlchemy intentionally doesn't auto-commit every object that has pending changes, that could result in unwanted or unexpected behaviour. You must add changed objects to your current session when you want to commit their changes. `db.session.add(custObj)` before you commit should do it. – daveruinseverything May 24 '18 at 03:50
  • what about NON JSON object which also opened (session.add) before? i created object and added onStart and updating while using (not closing the object) and at the end of the day trying to commit the status, and its not saving. BUT if I update if from the console (calling the class object with same session) it does. cannot get why. – aleXela Jun 14 '22 at 20:45

1 Answers1

5

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()
giuppep
  • 923
  • 1
  • 10
  • 20