【问题标题】:Sqlalchemy, trouble linking multiple columns. Foreign key Error.Sqlalchemy,链接多列时出现问题。外键错误。
【发布时间】:2016-06-25 18:08:49
【问题描述】:

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

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

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

我的声明代码:

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)

【问题讨论】:

    标签: python sqlalchemy foreign-keys


    【解决方案1】:

    因为,正如错误消息所说,ContactsActions 之间有多个外键,即 actions_idactions_action,所以它不知道您要使用哪个外键来建立关系 @ 987654325@。您可以通过指定(同样,如错误消息所示)foreign_keys 来修复它:

    actions = relationship(Actions, foreign_keys=actions_id)
    

    这修复了错误,但更好的问题是为什么除了actions_id 之外还需要actions_action

    【讨论】:

    • 这是否意味着我不能将 Actions 表中的附加列链接到 Contacts 表?
    • @ExperimentsWithCode 可以,但为什么需要?如果actions_id 单独完全识别Actions 中的一行,你打算让它做什么?加上Action.action 也不是唯一的,所以外键指向它是没有意义的。
    • 本质上,如果一个动作存在,我需要所有的列也存在,但如果一个不存在,则不需要填充这些字段。这就是为什么我把它们分成他们自己的桌子。但是,我希望能够根据分配给他们的操作对联系人进行排序。所以我真的想根据表 Actions 中的操作值过滤联系人。我觉得如果该值在联系人表中可见,那将是最简单的。
    • @ExperimentsWithCode 这不是外键的用途。您的特殊情况可以通过在查询时加入这两个表来解决,或者,您可以对数据进行非规范化并将操作值 复制contacts 表中,但您不应该有像这样的外键那个。
    • 太棒了。谢谢你。这是我第一次涉足 sql 类型的数据库,所以我仍然掌握了一些东西。非常感谢您的意见。
    猜你喜欢
    • 2019-05-22
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    相关资源
    最近更新 更多