Skip to content

Fix secondary relationship mapping #4

@NicolasJott

Description

@NicolasJott

When trying to filter by a relationship that is secondary to a pivot table, the following error occurs:

sqlalchemy.exc.InvalidRequestError: Don't know how to join to <AliasedInsp at 0x1167fcad0; Resource(Resource)>.
 Please use the .select_from() method to establish an explicit left side,
 as well as providing an explicit ON clause if not present already to help resolve the ambiguity.

An example of the types of fields that cause this to happen look like:

class Resource(Base):

    __tablename__ = "resources"

    id: Mapped[int]

   # pivot table relationship
    children_accounts: Mapped[List["ChildAccount"]] = relationship(
        back_populates="resource", cascade="all, delete"
    )

    # secondary relationship
    children: Mapped[List["Child"]] = relationship(
        secondary="children_accounts",
        overlaps="children_accounts, resource, child",
    )

Where children_accounts is the relation to the pivot table and children is the secondary relationship to children_accounts

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions