Daniel Robbins wrote:
> Hi All,
> 
> One of the things that doesn't seem to be covered in the 
> docs, and that I'm currently trying to figure out, is the 
> recommended design pattern to use for managing sessions from 
> declarative methods calls.
> 
> Consider a declarative class "User", where I want to 
> implement a "FindFriends() method:
> 
> class User(Base):
>       # declarative fields defined here
>       
>       def FindFriends(self):
>               session = Session()
>               # it's handy to use the "self" reference in 
> query methods:
>               friends = 
> session.query(Friends).filter_by(friend=self).all()
>               session.close()
>               return friends
> 
> Certainly, these types of methods would seem to be useful, 
> but here's a dilemma - the above code doesn't work. Because 
> the method uses a new session, which is guaranteed to not be 
> the same session that was used to retrieve the original User 
> object, the following code will fail:
> 
> session = session()
> me = session.query(User).filter_by(name="Daniel").first()
> me.FindFriends()
> 

See the 'How can I get the Session for a certain object' question at
http://www.sqlalchemy.org/docs/session.html#frequently-asked-questions

Basically, in your FindFriends method, replace:

   session = Session()

with:

   session = Session.object_session(self)

Hope that helps,

Simon

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalch...@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