Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join the same table in sqlalchemy

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?

like image 811
Gary van der Merwe Avatar asked Mar 10 '10 11:03

Gary van der Merwe


1 Answers

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)
              )
like image 106
Gary van der Merwe Avatar answered Oct 13 '22 12:10

Gary van der Merwe