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?