Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7177645
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T16:45:26+00:00 2026-05-28T16:45:26+00:00

I am trying to build a relationship to another many-to-many relationship, the code looks

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T16:45:27+00:00Added an answer on May 28, 2026 at 4:45 pm

    You need to map supervision_association_table so that you can create relationships to/from it.

    I may be glossing over something here, but it seems like since you have many-to-many here you really can’t have Client.schedules – if I say Client.schedules.append(some_schedule), which row in "supervision" is it pointing to?

    The example below provides a read-only "rollup" accessor for those which joins the Schedule collections of each SupervisorAssociation. The association_proxy extension is used to conceal, when convenient, the details of the SupervisionAssociation object.

    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
    from sqlalchemy.ext.associationproxy import association_proxy
    from itertools import chain
    
    Base = declarative_base()
    
    class SupervisionAssociation(Base):
        __tablename__ = 'supervision'
    
        supervisor_id = Column(Integer, ForeignKey('supervisor.id'), primary_key=True)
        client_id = Column(Integer, ForeignKey('client.id'), primary_key=True)
    
        supervisor = relationship("Supervisor", backref="client_associations")
        client = relationship("Client", backref="supervisor_associations")
        schedules = relationship("Schedule")
    
    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)
    
        clients = association_proxy("client_associations", "client", 
                            creator=lambda c: SupervisionAssociation(client=c))
    
        @property
        def schedules(self):
            return list(chain(*[c.schedules for c in self.client_associations]))
    
    class Client(User):
        __tablename__ = 'client'
        __mapper_args__ = {'polymorphic_identity': 'client'}
    
        id = Column(Integer, ForeignKey('user.id'), primary_key = True)
    
        supervisors = association_proxy("supervisor_associations", "supervisor", 
                            creator=lambda s: SupervisionAssociation(supervisor=s))
        @property
        def schedules(self):
            return list(chain(*[s.schedules for s in self.supervisor_associations]))
    
    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)
        client = association_proxy("supervisor_association", "client")
    
    engine = create_engine('sqlite:///temp.db', echo=True)
    db_session = scoped_session(sessionmaker(bind=engine))
    Base.metadata.create_all(bind=engine)
    
    c1, c2 = Client(), Client()
    sp1, sp2 = Supervisor(), Supervisor()
    sch1, sch2, sch3 = Schedule(), Schedule(), Schedule()
    
    sp1.clients = [c1]
    c2.supervisors = [sp2]
    c2.supervisor_associations[0].schedules = [sch1, sch2]
    c1.supervisor_associations[0].schedules = [sch3]
    
    db_session.add_all([c1, c2, sp1, sp2, ])
    db_session.commit()
    
    
    print c1.schedules
    print sp2.schedules
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to build a One to one relationship EF v4.1 Code first.
I was trying Build For Archiving application (from Titanium Mobile) with xCode 4.4, but
I'm trying build a method which returns the shortest path from one node to
Trying to build openssl-fips-2.0 with NDK, before I was lucky found this link and
Trying to build Xuggler under Windows. Xuggler is core native code functions wrapped into
I'm trying to build a modified role system that has the following class/relationship structure:
I am trying to build a friendship system sorta following this link: How to
I am having a problem trying to map out a many-to-many relationship , where
I am trying to build a relationship model between users. A user can either
I have the following code with which I'm trying to build a hierarchical /

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.