我的数据库模型有以下代码:
# account_manager.py
class AccountManager(User):
__tablename__ = 'account_managers'
id = Column(UUID(as_uuid=True), ForeignKey('users.id'), primary_key=True)
project_id = Column(Integer())
collaborators = relationship("CollaboratorUser", back_populates='manager')
__mapper_args__ = {
'polymorphic_identity': 'account_manager'
}
# collaborator_user.py
class CollaboratorUser(User):
__tablename__ = 'collaborators'
id = Column(UUID(as_uuid=True), ForeignKey('users.id'), primary_key=True)
manager_id = Column(UUID(as_uuid=True), ForeignKey('account_managers.id'))
manager = relationship("AccountManager", back_populates='collaborators',
foreign_keys=[manager_id])
__mapper_args__ = {
'polymorphic_identity': 'collaborator'
}
# user.py
class User(Base):
__tablename__ = 'users'
id = id_col()
email = Column(String)
full_name = Column(String)
temporary = Column(Boolean)
type = Column(String)
__mapper_args__ = {
'polymorphic_on': type
}
当我尝试加载模型时,出现以下错误:
发生异常:不明确的外键错误 无法确定关系上的父表/子表之间的联接条件 帐户管理器.协作者 - 有多个外键路径链接这些表。 指定 'foreign_keys' 参数,提供应计为包含对父表的外键引用的列的列表
我查找了这个错误,我看到的任何解决方案都与将foreign_keys
参数添加到关系函数有关。
任何帮助将不胜感激。
谢谢!
想通了。改变
manager = relationship("AccountManager", back_populates='collaborators',
foreign_keys=[manager_id])
自
manager = relationship("AccountManager", backref='collaborators',
foreign_keys=[manager_id])
并从AccountManager
中删除了collaborators
.这将自动将colloaborators
字段添加到AccountManager
。这似乎与文档不一致,但你去吧。