views:

55

answers:

1

Related (for the no-association-object use case): http://stackoverflow.com/questions/1889251/sqlalchemy-many-to-many-relationship-on-a-single-table

Building a many-to-many relationship is easy. Building a many-to-many relationship on the same table is almost as easy, as documented in the above question.

Building a many-to-many relationship with an association object is also easy.

What I can't seem to find is the right way to combine association objects and many-to-many relationships with the left and right sides being the same table.

So, starting from the simple, naïve, and clearly wrong version that I've spent forever trying to massage into the right version:

t_groups = Table('groups', metadata,
    Column('id', Integer, primary_key=True),
)

t_group_groups = Table('group_groups', metadata,
    Column('parent_group_id', Integer, ForeignKey('groups.id'), primary_key=True, nullable=False),
    Column('child_group_id', Integer, ForeignKey('groups.id'), primary_key=True, nullable=False),
    Column('expires', DateTime),
)

mapper(Group_To_Group, t_group_groups, properties={
    'parent_group':relationship(Group),
    'child_group':relationship(Group),
})

What's the right way to map this relationship?

+3  A: 

I guess you are getting an error like Could not determine join condition between parent/child tables... In this case, Change the mapper for Group_To_Group to the following:

mapper(Group_To_Group, t_group_groups, properties={
    'parent_group':relationship(Group,
        primaryjoin=(t_group_groups.c.parent_group_id==t_groups.c.id),),
    'child_group':relationship(Group,
        primaryjoin=(t_group_groups.c.child_group_id==t_groups.c.id),),
})

also you might want to add the backref so that you can navigate the relations from the Group objects as well.

van
I must have been doing something subtly wrong last night. That did it, though, thanks!
Nicholas Knight