pythonflaskflask-sqlalchemy

Flask-SQLAlchemy not saving database updates


I am trying to import data into existing database items. There are two fields that I want to update for each data base item: a string type field caled imagefolder and a picketype (list) field called images. The input values for both fields are strings that store file paths.

My steps are to query the database item, check for its existance, and then update its fields.

blend = Blend.query.filter_by(old_ID=row[4]).first()
if blend:
    blend.imagefolder = "/".join((row[16].split("/")[4:])[:-1])
    blend.images.append(ntpath.basename(row[16]))
    db.session.commit()

When I run the script nothing happens (the database doesn't update), and I noticed that the import script runs really quickly, too quickly.


Solution

  • You missed to add changed object to current session.

    And try the following snippet.

    blend = db.session.query(Blend).filter_by(old_ID=row[4]).first()
    if blend:
        blend.imagefolder = "/".join((row[16].split("/")[4:])[:-1])
        blend.images.append(ntpath.basename(row[16]))
        db.session.add(blend)
        db.session.commit()