Sqlalchemy,无法链接多个列。外键错误。

时间:2016-03-10 18:19:02

标签: python sqlalchemy foreign-keys

出于某种原因,当我尝试将Actions表的某个方面与我的联系人表链接时,我收到外键错误。我得到的错误是:

  

sqlalchemy.exc.AmbiguousForeignKeysError:无法确定关系Contacts.actions上的父/子表之间的连接条件    - 链接表有多个外键路径。指定'foreign_keys'参数,提供这些列的列表   应该被视为包含父表的外键引用。

我需要帮助理解为什么已经链接的表不适用于第二个属性。(请参阅下面代码中的注释所包围的行)

我的声明代码:

Base = declarative_base()

class Users(Base):
    __tablename__ = 'users'
    # Here we define columns for the table person
    # Notice that each column is also a normal Python instance attribute.
    id = Column(Integer, primary_key=True)
    username = Column(String(30), nullable=False)
    first_name =  Column(String(20), nullable=False)
    last_name =  Column(String(20), nullable=False)
    email =  Column(String(40), nullable=False)
    phone =  Column(String(10), nullable=False)
    #default_duration =  Column(Integer(2))

class Actions(Base):
    __tablename__ = 'actions'
    id = Column(Integer, primary_key=True)
    action = Column(String(15), nullable=False)
    message =  Column(String(140), nullable=False)
    duration =  Column(Integer(2), nullable=False)



class Contacts(Base):
    __tablename__ = 'contacts'
    # Here we define columns for the table address.
    # Notice that each column is also a normal Python instance attribute.
    id = Column(Integer, primary_key=True)
    contact_name = Column(String(30), nullable=False)
    time_of_last_message = Column(String(40))
    message_log = Column(String(450))
    users_id = Column(Integer, ForeignKey('users.id'), nullable=False)
    users = relationship(Users)

     ##############################
    #### If this line is commented it out, it works
    #### But If it is present I get the error
    actions_action = Column(String, ForeignKey('actions.action'))
    ####
    ###############################

    actions_id =  Column(Integer, ForeignKey('actions.id'))
    actions = relationship(Actions)

1 个答案:

答案 0 :(得分:1)

因为,正如错误消息所示,您在ContactsActions之间有多个外键,即actions_idactions_action,因此它不知道您希望将哪一个用于关系actions。您可以通过指定(再次,如错误消息所示)foreign_keys

来修复它
actions = relationship(Actions, foreign_keys=actions_id)

这可以修复错误,但更好的问题是除actions_action之外还需要actions_id的原因吗?