Background
The get()
method is special in SQLAlchemy's ORM because it tries to return objects from the identity map before issuing a SQL query to the database (see the documentation).
This is great for performance, but can cause problems for distributed applications because an object may have been modified by another process, so the local process has no ability to know that the object is dirty and will keep retrieving the stale object from the identity map when get()
is called.
Question
How can I force get()
to ignore the identity map and issue a call to the DB every time?
Example
- I have a
Company
object defined in the ORM. - I have a
price_updater()
process which updates thestock_price
attribute of all theCompany
objects every second. - I have a
buy_and_sell_stock()
process which buys and sells stocks occasionally.- Now, inside this process, I may have loaded a
microsoft = Company.query.get(123)
object. - A few minutes later, I may issue another call for
Company.query.get(123)
. The stock price has changed since then, but mybuy_and_sell_stock()
process is unaware of the change because it happened in another process. - Thus, the
get(123)
call returns the stale version of theCompany
from the session's identity map, which is a problem.
- Now, inside this process, I may have loaded a
I've done a search on SO(under the [sqlalchemy] tag) and read the SQLAlchemy docs to try to figure out how to do this, but haven't found a way.