Sqlalchemy: Association object for 3 tables with many-to-many relationship

Viewed 616

I'm working on a project and I have 3 entities that need to be mapped together with many-to-many relationship. let's say my tables are A, B and C. I want to be able to know which Bs and Cs are associated with A and the same thing for B (wich As and Cs are associated) and the same thing for C.

I tried to implement this using Sqlalchemy and this how my code looks like:

class A(Base):
    __tablename__ = 'a'
    a_id = Column(Integer, primary_key=True)

    b_children = relationship("Association")
    c_children = relationship("Association")

class B(Base):
    __tablename__ = 'b'
    b_id = Column(Integer, primary_key=True)

    a_children = relationship("Association")
    c_children = relationship("Association")

class C(Base):
    __tablename__ = 'c'
    c_id = Column(Integer, primary_key=True)

    b_children = relationship("Association")
    c_children = relationship("Association")

class Association(Base):
    __tablename__ = 'associations'
    a_id = Column(Integer, ForeignKey('a.a_id'))
    b_id = Column(Integer, ForeignKey('b.b_id'))
    c_id = Column(Integer, ForeignKey('c.c_id'))

I know it shouldn't be this simple so I'm wondring if this is correct or not.. because I want for example to be able to do a = A() and b = B() and a.b_childern.append(b)

0 Answers
Related