Sobes.tech
Junior — Middle

What is the difference between the commit command and the flush method when using SQLAlchemy?

sobes.tech AI

Answer from AI

In SQLAlchemy, the flush() method sends all accumulated changes from the session to the database but does not commit the transaction — meaning changes become visible in the database, but the transaction remains open and can be rolled back. This is useful, for example, to get database-generated values (like IDs) before final commit.

The commit() command, on the other hand, not only calls flush() but also ends the transaction, making all changes permanent in the database. After commit(), changes are visible to other transactions.

Example:

session.add(new_user)  # Add object
session.flush()        # Send changes to DB but do not commit
print(new_user.id)     # Can get generated ID
session.commit()       # Commit transaction