0

In the SQLAlchemy documentation there is this nice example about Many to Many relations. See the second code block at: http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#many-to-many

I would like to do the same, but with a single data table, so that both parent(s) and child(ren) of an object are of the same type.

What I've tried is something like this:

association_table = Table('association', Base.metadata,
    Column('left_id', Integer, ForeignKey('mytable.id')),
    Column('right_id', Integer, ForeignKey('mytable.id'))
)

class MyTable(Base):
    __tablename__ = 'mytable'
    id = Column(Integer, primary_key=True)
    children = relationship(
        "MyTable",
        secondary=association_table,
        back_populates="parents")
    parents = relationship(
        "MyTable",
        secondary=association_table,
        back_populates="children")

Unfortunately, this produces an error message:

sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship MyTable.children - there are multiple foreign key paths linking the tables via secondary table 'association'.  Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference from the secondary table to each of the parent and child tables.

I do understand the error and why it happens, but I cannot really figure out, how to solve it in SQLAlchemy. Can anyone please help? Thanks.

Cheers, Tim

The_Fallen
  • 257
  • 1
  • 3
  • 10

0 Answers0