tags:

views:

322

answers:

2

I'm trying to join the same table in sqlalchemy. This is a minimial version of what I tried:

#!/usr/bin/env python
import sqlalchemy as sa
from sqlalchemy import create_engine
from sqlalchemy.orm import mapper, sessionmaker, aliased

engine = create_engine('sqlite:///:memory:', echo=True)

metadata = sa.MetaData()
device_table = sa.Table("device", metadata,
    sa.Column("device_id", sa.Integer, primary_key=True),
    sa.Column("name", sa.String(255), nullable=False),
    sa.Column("parent_device_id", sa.Integer, sa.ForeignKey('device.device_id')),
    )

class Device(object):
    device_id = None
    def __init__(self, name, parent_device_id=None):
        self.name = name
        self.parent_device_id = parent_device_id

    def __repr__(self):
        return "<Device(%s, '%s', %s)>" % (self.device_id,
                                           self.name,
                                           self.parent_device_id )

mapper(Device, device_table)

metadata.create_all(engine)

db_session = sessionmaker(bind=engine)()

parent = Device('parent')
db_session.add(parent)
db_session.commit()

child = Device('child', parent.device_id)
db_session.add(child)
db_session.commit()

ParentDevice = aliased(Device, name='parent_device')
q = db_session.query(Device, ParentDevice)\
    .outerjoin(ParentDevice,
               Device.parent_device_id==ParentDevice.device_id)

print list(q)

This gives me this error:

ArgumentError: Can't determine join between 'device' and 'parent_device'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.

But I am specifying a onclause for the join. How should I be doing this?

+1  A: 

Your mapper should specificy the connection between the two items, here's an example: adjacency list relationships

WoLpH
I could not get this to work for the above example, but thanks for the pointer to that doc. It introduced me to some parts of sqlalchemy that I was not aware of, which will be useful to me in other parts of my app.
Gary van der Merwe
+1  A: 

For query.[outer]join, you specify as list of joins (which is different to expression.[outer]join.) So I needed to put the 2 elements of the join, the table and the onclause in a tuple, like this:

q = db_session.query(Device, ParentDevice)\
    .outerjoin(
                  (ParentDevice, Device.parent_device_id==ParentDevice.device_id)
              )
Gary van der Merwe