On Feb 20, 2014, at 3:22 PM, Jonathan Vanasco <jonat...@findmeon.com> wrote:

> this seems to work, but I want to just make sure this is the intended 
> behavior.
> 
>    a = dbSession.query( Something ).filter( Something.primary_key == 1 
> ).first()
>    b = dbSession.query( Something ).get( 1 )
>    c = dbSession.query( Something ).get( 1 )
>    d = dbSession.query( Something ).get( 1 )
>    e = dbSession.query( Something ).get( 1 )
> 
> in the above example , we will only hit the database once , because the 
> 'filter' populates the local session map with the primary key.  right ?

yes.   As long as you maintain a reference to the object outside of the session.

I use this pattern when I am dealing with lots of data that has a bunch of many 
to ones.  Suppose Player objects have a many-to-one to a Sport.  We have large 
N number of players and just a handful of Sports.   So i do this:

sports = set(sess.query(Sport))  # one SELECT.  hold onto “sports” for the 
duration

for player in sess.query(Player):  # one SELECT
   # …
   player.sport   # uses get(), no SELECT

this is not too different from using “subquery eager loading” except the 
queries are straight SELECT with no joins or subqueries.



Attachment: signature.asc
Description: Message signed with OpenPGP using GPGMail

Reply via email to