AmbiguousForeignKeysError:无法确定关系User_address.user上的父/子表之间的连接条件 - 有多个链接表的外键路径。指定'foreign_keys'参数,提供应列为包含父表的外键引用的列的列表。
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
phone = Column(String, nullable=False)
password = Column(String, nullable=False)
nickname = Column(String)
default_address_id = Column(Integer,ForeignKey('user_address.id'))
default_address = relationship('User_address')
class User_address(Base):
__tablename__ = 'user_address'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('user.id'), nullable=False)
user = relationship('User', backref='addresses')
address = Column(String, nullable=False)
lng = Column(Integer, nullable=False)
lat = Column(Integer, nullable=False)
如何解决这个问题
答案 0 :(得分:0)
这是mutually-dependent关系的示例,因为user_address.user_id
引用user
,但user.default_address_id
引用user_address
。
按照文档中的示例并根据您的用例进行调整会产生如下内容:
from sqlalchemy import Integer, String, ForeignKey, Column
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
Base = declarative_base()
class User_address(Base):
__tablename__ = 'user_address'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('user.id'), nullable=False)
address = Column(String, nullable=False)
lng = Column(Integer, nullable=False)
lat = Column(Integer, nullable=False)
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
phone = Column(String, nullable=False)
password = Column(String, nullable=False)
nickname = Column(String)
default_address_id = Column(Integer,ForeignKey('user_address.id'))
addresses = relationship(User_address, backref='user',
primaryjoin=
id==User_address.user_id
)
default_address = relationship(User_address,
primaryjoin=
default_address_id==User_address.id,
post_update=True)
解析AmbiguousForeignKeysError
的技巧是primaryjoin参数,它告诉关系映射器显式使用哪些SQL连接条件。