I am trying to build a relationship to another many-to-many relationship, the code looks like this:
from sqlalchemy import Column, Integer, ForeignKey, Table, ForeignKeyConstraint, create_engine
from sqlalchemy.orm import relationship, backref, scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
supervision_association_table = Table('supervision', Base.metadata,
Column('supervisor_id', Integer, ForeignKey('supervisor.id'), primary_key=True),
Column('client_id', Integer, ForeignKey('client.id'), primary_key=True)
)
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
class Supervisor(User):
__tablename__ = 'supervisor'
__mapper_args__ = {'polymorphic_identity': 'supervisor'}
id = Column(Integer, ForeignKey('user.id'), primary_key = True)
schedules = relationship("Schedule", backref='supervisor')
class Client(User):
__tablename__ = 'client'
__mapper_args__ = {'polymorphic_identity': 'client'}
id = Column(Integer, ForeignKey('user.id'), primary_key = True)
supervisor = relationship("Supervisor", secondary=supervision_association_table,
backref='clients')
schedules = relationship("Schedule", backref="client")
class Schedule(Base):
__tablename__ = 'schedule'
__table_args__ = (
ForeignKeyConstraint(['client_id', 'supervisor_id'], ['supervision.client_id', 'supervision.supervisor_id']),
)
id = Column(Integer, primary_key=True)
client_id = Column(Integer, nullable=False)
supervisor_id = Column(Integer, nullable=False)
engine = create_engine('sqlite:///temp.db')
db_session = scoped_session(sessionmaker(bind=engine))
Base.metadata.create_all(bind=engine)
What I want to do is to relate a schedule to a specific Client-Supervisor-relationship, though I have not found out how to do it. Going through the SQLAlchemy documentation I found a few hints, resulting in the ForeignKeyConstraint on the Schedule-Table.
How can I specify the relationship to have this association work?