Search code examples
pythonsqlalchemyfalconframework

Add and update with sqlalchemy in single commit


I am new in sqlalchemy. I want to do add and update in single transaction for same model.code snippet is below. Application throwing error like 'Session' object has no attribute 'update'

current_date = datetime.datetime.now()
try:
    session = Session()
    user = UserProvision()
    user.username = admin["username"]
    user.password= admin["password"]
    user.client_id= admin["client_id"]
    user.fname= admin["fname"]
    user.lname= admin['lname']
    user.phone= admin['phone']
    session.add(user)
    session.flush()
    user_id = user.user_id
    user.name = admin["fname"]+" "+admin["lname"]
    user.setCreated_by=user_id
    user.setModified_by=user_id
    user.setCreated_name=admin["fname"]+" "+admin["lname"]
    user.setModified_name=admin["fname"]+" "+admin["lname"]
    user.setLast_reset_date=current_date
    user.setLast_reset_by = current_date
    session.update(user)
    session.flush()
    session.commit()
except Exception as ex:
    print ex.__str__()
finally:
    session.close()

Solution

  • When you've added the model object to the session its state is already tracked for changes. There's no need to explicitly mark it as updated, and as you've noted there is no such method Session.update(). Simply remove that line and your code should work as expected.

    The tracking is achieved through instrumentation of model class attributes:

    The SQLAlchemy mapping process, among other things, adds database-enabled descriptors to a mapped class which each represent a particular database column or relationship to a related class.

    In other words when your model class is constructed the Column attributes will be replaced with InstrumentedAttribute descriptor instances that among other things keep track of changes to the value.

    Note that there's no need to manually flush just before Session.commit():

    Flush pending changes and commit the current transaction.