0

I have two tables. The first table has a compound primary key. I want to join the second table to the first using those two columns as foreign keys. Below is the simplified code to show the issue:

class Table_A(Base):
   __tablename__ = 'Table_A'
   Path = Column(String, primary_key=True)
   Name = Column(String, primary_key=True)
   Group = Column(String)

class Table_B(Base):
   __tablename__ = 'Table_B'
   Path = Column(String, ForeignKey('Table_A.Path', primary_key=True)
   Name = Column(String, ForeignKey('Table_A.Name', primary_key=True)
   Result = Column(Float)
   table_a = relationship("TableA", foreign_keys=[Path, Name])

When I try to load this model, I get the the error "AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Table_A.table_b - there are multiple foreign key paths linking the tables. Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference to the parent table."

As you can see above, I do have the foreign_keys set for this relationship.

Extra info - I'm trying to get to the point I can do the equivalent of this join

select Table_B.Path, Table_B.Name, Table_A.Group, Table_B.Result
    from Table_B join Table_A
    on Table_A.Path = Table_B.Path and Table_A.Name=Table_B.Name;
ppovoski
  • 4,553
  • 5
  • 22
  • 28
  • I think you need to specify `foreign_keys` as string as follows: `table_a = relationship("TableA", foreign_keys=["TableA.Path", "TableA.Name"]` – metmirr Dec 04 '17 at 21:39
  • please add the error message to your post - usually that shows the failed join – brddawg Dec 04 '17 at 21:54
  • Error message is included in the post already. See above. – igilmore Dec 04 '17 at 22:39
  • Kudos to those who saw this was a duplicate. Their stackoverflow search skills are greater than mine. The answer is in the linked question - it needs a compound "__table_args__ = (ForeignKeyConstraint([Path, Name], ["Table_A.Path", "Table_A.Name"]), {})" instead of the individual per column ForeignKey's. – igilmore Dec 04 '17 at 22:47

0 Answers0