sqlalchemy,AmbiguousForeignKeysError

时间:2014-11-17 05:16:13

标签: python sqlalchemy

我写了两个模型,一个是“User”,另一个是“User_address”,它们之间有另外一个外键点,然后出现了以下问题

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)

如何解决这个问题

1 个答案:

答案 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连接条件。