On Sep 25, 2012, at 1:25 PM, Eduardo wrote:

> Hi,
> I am trying to find some efficient way to query objects stored in the session.
> Do I have to loop through the session to find all objects which names are 
> John for example or there is some more efficient way to do this.
> The filter() would be perfect but it is not applicable for the session 
> objects.

The Session intrinsically only stores objects by "identity key", that is, the 
class of object as well as the primary key value we have for it in memory.   
They aren't indexed in memory in any other way besides that, as well as whether 
or not they are "new", "dirty" or "deleted".

The way the Session works, that is using an identity map, the effect that you 
get when you query the database is actually that you get those in-memory 
objects back when a database query matches those particular rows.   So to that 
extent, the usual way that you query objects where "name='John'" already has 
this effect.

So with that out of the way, I'm assuming you're going for one of two things:   
1. you want to get the objects from the Session without any SQL emitted, for 
performance reasons, or 2. you really just want objects that are already loaded 
in memory; i.e. this is sort of like an additional "filter" criterion 
(name='John' AND "object in memory").

Other than just iterating through all the objects in memory, I think if you 
really need this kind of thing it might be worth it to create in-memory 
indexes.  You could even get pretty fancy with it.    I found this case to be 
interesting so I created a usage recipe at: 
http://www.sqlalchemy.org/trac/wiki/UsageRecipes/SessionIndexing .

However, it still has caveats.   If you change the name of a User to something 
else, it would need to be re-indexed, which this example doesn't support.   



-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to