Archive for October 21st, 2009

Filed Under (Python) by Ɓukasz Balcerzak on October-21-2009

While I love many things about SQLAlchemy this was something I just missed sooooo much – defining model’s methods without having to pass session object.
While using Django ORM for such action it is extra easy as there is no session objects at all (well, there is connection object but it’s much simpler and less sophisticated).
Assume you have BlogEntry and BlogComment mappers and you want to define function at entry model which returns related comments – I know, it is as simple as it could be, but it’s only an example.

class BlogEntry(Base):
    __tablename__ = 'blog_entry'

    title = Column(String)
    content = Column(Text)
    created_at = Column(DateTime, default=datetime.datetime.now)

    def __repr__(self):
        return self.title

class BlogComment(Base):
    __tablename__ = 'blog_comment'

    content = Column(Text)
    created_at = Column(DateTime, default=datetime.datetime.now)
    entry_id = Column(Integer, ForeignKey('blog_entry.id'))
    entry = relation('BlogEntry',
        primaryjoin='BlogEntry.id==BlogComment.entry_id',
        backref='comment_set')

You now can of course get comments using comment_set attribute on blog entry. But sometimes we want start querying for other objects, for some reasons.
With Django ORM, no problem, just define method on the model and start querying – it just works. With SQLAlchemy on the other hand we need to create query
using Session object. But how does mapper use proper session if you call ‘comment_set’? Well, I’ve found the answer here: http://www.sqlalchemy.org/docs/05/reference/orm/sessions.html . There is ‘Session.object_session’ class method which returns session object binded to an model object.

So now we can simply define method for BlogComment:

    def get_related_comments(self):
        session = Session.object_session(self)
        comment_list = session.query(BlogComment)\
            .filter(BlogComment.entry_id==BlogEntry.id)\
            .all()
        return comment_list

Just remember that object which is passed to ‘Session.object_session’ method has to be binded with some session first.