use mutliple foreign keys

Question:

I have a table with a composite primary key, these two columns are then used as both primary and foreign key for another table, but I can not seem to create the relationship in sqlalchemy.

I get the following error

sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Parent.children - 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.

This is my code, how can I fix this?

from sqlalchemy import create_engine, Column, ForeignKey, Integer
from sqlalchemy.orm import declarative_base, relationship

Base = declarative_base()

class Parent(Base):
    __tablename__ = "parent"
    id_1 = Column(Integer, primary_key=True, unique=True)
    id_2 = Column(Integer, primary_key=True, unique=True)
    children = relationship("Child", back_populates="parent", foreign_keys='[Child.f_id_1,Child.f_id_2]')

class Child(Base):
    __tablename__ = "child"
    f_id_1 = Column(Integer, ForeignKey(Parent.id_1), primary_key=True)
    f_id_2 = Column(Integer, ForeignKey(Parent.id_2), primary_key=True)
    parent = relationship(Parent, back_populates="children", foreign_keys='[Child.f_id_1,Child.f_id_2]')


engine = create_engine("postgresql://user:pass@localhost:5432", future=True)

Base.metadata.create_all(engine)

from sqlalchemy.orm import Session

with Session(engine) as session:
    session.add(Parent())

Asked By: nvhrw

||

Answers:

Looks like you need to supply a ForeignKeyConstraint, or else SqlAlchemy won’t understand that the values should be paired together.

class Child(Base):
    __tablename__ = "child"
    f_id_1 = Column(Integer, primary_key=True)
    f_id_2 = Column(Integer, primary_key=True)

    __table_args__ = (
        ForeignKeyConstraint([f_id_1, f_id_2], [Parent.id_1, Parent.id_2]),
        {},
    )
Answered By: Kevin
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.