Is it possible to use a couple of fields not from the primary key to retrieve items (already fetched earlier) from the identity map? For example, I often query a table by (external_id, platform_id)
pair, which is a unique key, but not a primary key. And I want to omit unnecessary SQL queries in such cases.
SQLAlchemy get items from the identity map not only by primary key
7.2k Views Asked by Ivan Velichko At
2
There are 2 best solutions below
1

It's possible to access the whole identity map sequentially:
for obj in session.identity_map.values():
print(obj)
To get an object by arbitrary attributes, you then have to filter for the object type first and then check your attributes.
It's not a lookup in constant time, but can prevent unnecessary queries.
There is the argument, that objects may have been modified by another process and the identity map doesn't hold the current state, but this argument is invalid: If your transaction isolation level is read committed
(or less) - and this is often the case, data ALWAYS may have been changed immediately after the query is finished.
A brief overview of identity_map and get():
An identity map is kept for a lifecycle of a SQLAlchemy's
session
object i.e. in case of a web-service or a RESTful api thesession
object's lifecycle is not more than a singlerequest
(recommended).From : http://martinfowler.com/eaaCatalog/identityMap.html
In SQLAlchemy's ORM there's this special query method
get()
, it first looks intoidentity_map
using the pk (only allowed argument) and returns object from the identity map, actually executing theSQL
query and hitting the database.From the docs:
Only
get()
is using theidentity_map
- official docs:P.S. If you're querying not using
pk
, you aren't hitting theidentity_map
in the first place.Few relevant SO questions, helpful to clear the concept:
Forcing a sqlalchemy ORM get() outside identity map