G
G
gpm73152018-08-24 21:21:25
Python
gpm7315, 2018-08-24 21:21:25

Why doesn't SQLAlchemy update an object after requerying it?

Hey! SQLAlchemy is designed in such a way that when a session repeatedly requests the same row from the database within a transaction, it does not update the object corresponding to it, which was formed during the first request. Those. having received an object once, its repeated request in a transaction will not change the object, although the values ​​in the database could have already been changed.

alex = session.query(User).filter_by(name='Alex').first()
# в этот момент соответствующая запись в БД изменяется другим процессом
alex = session.query(User).filter_by(name='Alex').first()
# объект alex не изменится и будет соответствовать первому запросу, т.е. по сути у объекта останутся устаревшие данные, не соответствующие текущему состоянию БД
session.commit()

Can you please help me figure out what is the reason for this behavior?
The explanation in the docs is rather unclear:
The session cannot fully predict when the same SELECT query executed a second time will necessarily return the same data that we already have, or it will be new data.

Why not just update the object's attributes with the data retrieved from the database, new or old?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Arkhipov, 2019-01-02
@diman40

As I understand it, you need to look towards the transaction isolation mode for the selected database.
In the case of MySQL + SQLAlchemy, you can try this:

create_engine(DB_URL, isolation_level='READ COMMITTED')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question