Whenever I try to establish an adjacency list relationship within a
child class (Department --> Parent Department in this case) the orm
complains about foreign key columns present in both the parent and
child class, and won’t construct the mapping. Below is an example
illustrating the problem. I'd appreciate any insight.

Thanks,
Michael Naber


from sqlalchemy.orm import scoped_session, sessionmaker, relationship,
backref
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Column, Integer, String,
ForeignKey, Text, Date

Session = scoped_session(sessionmaker())
Base = declarative_base()

engine = create_engine('sqlite:///data.db')
Session.configure(bind=engine)

class Node(Base):
    __tablename__ = 'node'
    id = Column(Integer, primary_key=True)
    name = Column(String(100))
    discriminator = Column('discriminator', String(50))


class Department(Node):
    __tablename__ = 'department'
    __mapper_args__ = {'polymorphic_identity': 'department'}
    id = Column(Integer, ForeignKey('node.id'), primary_key=True)
    description = Column(Text)
    parent_department_id = Column(Integer,
ForeignKey('department.id'))
    parent_department = relationship("Department",
 
primaryjoin="Department.parent_department_id==Department.id",
 
foreign_keys="Department.parent_department_id",
 
backref=backref("subdepartments"), remote_side="Department.id")

Base.metadata.drop_all(checkfirst=True, bind=Session.bind)
Base.metadata.create_all(bind=Session.bind)

s = Session()

d = Department(name='Great Department', description='some text')
s.add(d)
s.commit()

for dept in s.query(Department).all():
    print dept.id
    print dept.name

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to