All, thanks for taking the time to help. Basically, I have a table called Task that has a one-to-many relationship with a table called Label. This works just fine. I can assign every label I create to a task ID and then I can query labels by the task id. But I would also like to have a one-to-many relationship in reverse so every label can have a relationship with all tasks. Hope that makes sense. This is all pretty new to me so maybe I’m going about it all wrong. Maybe I’m making it too complicated and should remove all relationships and just create a column in each table that stores the information. I was hoping to take advantage of some of the things that come with having a relationship though.
Here are my classes with a lot of extra stuff removed to make it easier to view.
class Task(Base):
__tablename__ = 'tasks'
# This works fine
labels: Mapped[List["Task"]] = relationship(
"Label",
back_populates="task",
)
# I then added these for the reverse one-to-many and get the error
label_id: Mapped[PYTHON_UUID] = mapped_column(
UUID,
ForeignKey("labels.id"),
)
label: Mapped["Label"] = relationship(
"Label",
back_populates="task_ids"
)
# this is a different one-to-many relationship that goes to a Comment table. This
# works okay too, but maybe it's relevant?
comments: Mapped[List["Task"]] = relationship(
"Comment",
back_populates="task",
cascade="all, delete",
)
class Label(Base):
__tablename__ = 'labels'
# These work fine
task_id: Mapped[Optional[PYTHON_UUID]] = mapped_column(
UUID,
ForeignKey("tasks.id"),
nullable=False,
)
task: Mapped[List[Task]] = relationship(
"Task",
back_populates="labels"
)
# I then added this for the reverse one-to-many and get the error
tasks: Mapped[List["Label"]] = relationship(
"Task",
back_populates="label",
)
This is the error:
sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Task.labels – 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.
It sounds like maybe I just need to add the ‘foreign_keys’ argument, but I’m a little lost on how to accomplish that with what I’m trying to do.
Here are some of the relevant libraries I’m using:
- SQLAlchemy: 2.0.31
- fastapi: 0.111.0
- asyncpg: 0.29.0
- pydantic: 2.8.2
- pydantic_core: 2.20.1
TIA,
Jon