dimachidy
dimachidy

Reputation: 110

Is it wasteful to commit unchanged objects to database with sqlalchemy?

Let's say I have an object in memory from my database that I retrieved using sqlalchemy like this:

user_object = database_session.query(User).first()

I do a few checks on this object that don't change anything, like this (for this example my user_object has name property equal to "John"):

if user_object.name == "John": 
    do nothing
else:
    do something

I then add this object to a list that will get committed to the database at once, with this operation in mind:

objects_list.append(user_object)
database_session.add_all(objects_list)
database_session.commit()

Some of the objects in objects_list will have changes, some will not.

Is this process of committing a number of unchanged objects wasteful, and if so what is a better way to handle this situation?

Upvotes: 0

Views: 320

Answers (1)

Ilja Everilä
Ilja Everilä

Reputation: 52947

When you do

user_object = database_session.query(User).first()

the loaded object is already in the session. From there on the session tracks changes to the object through instrumentation. Session.add() and Session.add_all() simply ignore objects that are already in the session, so

objects_list.append(user_object)
database_session.add_all(objects_list)

is at least partly redundant. When you call Session.commit() SQLAlchemy will first flush any pending changes held in the Session to the database and then commits. In other words you're not committing any "unchanged objects".

Upvotes: 1

Related Questions