python config_error ai_generated true

sqlalchemy.exc.AmbiguousForeignKeysError:无法确定父/子表之间的连接条件——存在多个外键路径链接表。请指定 'foreign_keys' 参数。

sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship User.addresses - there are multiple foreign key paths linking the tables. Specify the 'foreign_keys' argument.

ID: python/sqlalchemy-ambiguous-foreign-key

其他格式: JSON · Markdown 中文 · English
80%修复率
85%置信度
0证据数
2024-06-18首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

两个表之间存在多个外键,未指定显式连接条件。

English

Multiple foreign keys between two tables without explicit join condition.

generic

解决方案

  1. 95% 成功率 Specify 'foreign_keys' argument in relationship.
    class User(Base):
        __tablename__ = 'users'
        id = Column(Integer, primary_key=True)
        addresses = relationship('Address', foreign_keys='Address.user_id')
  2. 90% 成功率 Use primaryjoin explicitly.
    addresses = relationship('Address', primaryjoin='User.id == Address.user_id')

无效尝试

常见但无效的做法:

  1. Removing one foreign key constraint from the database. 50% 失败

    Destructive and may break data integrity; not necessary.

  2. Setting primaryjoin with a string that doesn't match columns. 70% 失败

    String must be a valid SQL expression; typos cause errors.