Max Ischenko wrote:
> 
> Hi,
> 
> If I have two tables related via foreign key how can I tell SA that
> accessing foreign key should fetch related object automatically? By
> default it simply gives me the FK as integer which is not what I want.
> 
> Here are my mappers:
> 
>     wp_users_tbl = Table('wp_users', meta, autoload=True)
>     wp_posts_tbl = Table('wp_posts', meta,
>             Column('post_author', Integer,
> ForeignKey(wp_users_tbl.c.ID)),
>             autoload=True)
> 
>     mapper(WordpressPost, wp_posts_tbl)
>     mapper(WordpressUser, wp_users_tbl, properties={
>             'posts' : relation(WordpressPost),
>    })
> 
> >>> post = db.select_one(...)
> >>> print post.post_author # prints 123 instead of 
> WordpressUser instance
> 
> Thanks,
> Max.

You're halfway there with your 'posts' relation. I think if you pass
backref='author' in your relation, then WordpressPost objects will get
an 'author' property which points back to the WordpressUser. Relations
are described more fully here:

http://www.sqlalchemy.org/docs/datamapping.html#datamapping_relations

The property pointing to the WordpressUser instance is separate from the
property containing the foreign key value. If you want the property to
be named 'post_author', you'll need to rename the foreign key
relationship to prevent them clashing. You can either rename your
ForeignKey column, or override the column name as described here:

http://www.sqlalchemy.org/docs/adv_datamapping.html#advdatamapping_prope
rties_colname

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 [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
-~----------~----~----~----~------~----~------~--~---

Reply via email to