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()
It would seem to be handy if SQLAlchemy placed a reference in each declarative
object of the session from which it originated when query was called, so then
my code could do something like this:
class User(Base):
# declarative fields defined here
def FindFriends(self):
# note the "self.session.query" - the idea is that sqlalchemy's
query() would initialize this for us
return self.session.query(Friends).filter_by(friend=self).all()
Then this would allow the following code to work:
session = session()
me = session.query(User).filter_by(name="Daniel").first()
me.FindFriends()
This would work because me.FindFriends() would now have easy access to the same
session that was used to retrieve "me" -- so the objects would be "compatible"
and could be easily combined in queries. This would allow many methods to be
added to the User class that could all do various kinds of db queries without
having to pass a session variable around manually.
My question is - what is the recommended design pattern to do what I am trying
to do above? Passing the current session as an argument to FindFriends() seems
cumbersome - is that the recommended approach or is there a more elegant way to
handle it? Is my "handy" suggestion above something that would actually be
useful or is there a better way to do what I am wanting to do?
(I'm trying to be a good SQLAlchemy coder and not use a global
session=Session() for everything, as explained here:
http://www.sqlalchemy.org/docs/session.html#frequently-asked-questions . But to
do this, I need to find a good design pattern to use in place of a global :)
Thanks and Regards,
Daniel
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en.