views:

90

answers:

1

I have three tables (users, articles, and tags) defined in SQLAlchemy and mapped with orm.mapper(). As you can see below, I'm adding a property "author" to each article which ties that article to the user that created it.

orm.mapper(User, t_users)
orm.mapper(Tag, t_tags)
orm.mapper(Article, t_articles, properties={
    'author' : orm.relation(User),
    'tags' : orm.relation(Tag, secondary=t_tags_articles),
    })

I'm listing an index of articles, and each article will need to show its tags and its author. I'm trying to figure out the best way (minimal SQL queries, better performance) to retrieve the author and tags data.

If I do this:

results = Session.query(Article).all()

then I can pull the author and tags for each article in the index like this:

author = results[0].author
tags = results[0].tags

but this runs two new queries for each results[x] that I loop through (yikes). If I do this:

results = Session.query(Article, User).join('author').all()

then I can access the author data like this (because it's joined in):

firstname = results[0].firstname

but trying to get a list of tags doesn't work, and instead raises an AttributeError ('rowTuple' object has no attribute 'tags'):

tags = results[0].tags

What am I doing wrong, and what's the best way to access the data for this index?

+2  A: 

Considered eagerloading, as covered in Working with Related Objects?

Your join is also funky. You're mixing the ORM with the SQL-toolkit, so you're getting row-objects and not mapped objects back. See Querying with Joins

Alex Brasetvik
Thanks. That's exactly what I needed.
Travis