SQLAlchemy一对多关系错误

1 投票
1 回答
1563 浏览
提问于 2025-04-17 19:47

我在使用SQLAlchemy(0.8)时遇到了一个一对多的关系:

class Parent(Base):

    __tablename__ = "parents"

    cid = Column(Integer(11), primary_key = True, autoincrement = False)
    uid = Column(Integer(11), ForeignKey('otherTable.uid',
           ondelete = 'CASCADE'), primary_key = True)
    ...

    # Relationship with child
    childs_rel = relationship("Child", backref = 'parents', 
                              cascade = "all, delete-orphan")

还有

class Child(Base):

    __tablename__ = "childs"

    mid = Column(Integer(11), primary_key = True, autoincrement = False)
    cid = Column(Integer(11), ForeignKey('parents.cid',
           ondelete = 'CASCADE'), primary_key = True)
    uid = Column(Integer(11), ForeignKey('parents.uid',
           ondelete = 'CASCADE'), primary_key = True)
    ...

我可以创建这个数据库,但当我尝试操作它时,出现了这个错误:

sqlalchemy.exc.AmbiguousForeignKeysError: 无法确定父表和子表之间的连接条件,关系Parent.childs_rel存在多个外键路径连接这些表。请指定'foreign_keys'参数,提供一个包含外键引用父表的列的列表。

我尝试在childs_rel中指定'foreign_keys',但系统提示在Parent类中没有外键,这确实是对的……外键必须在子类中指定,但根据SQLAlchemy的ORM文档,关系是在“一”这一方定义的,也就是“一对多”关系中的“一”...

http://docs.sqlalchemy.org/en/rel_0_8/orm/relationships.html#one-to-many

你觉得这里发生了什么呢?非常感谢!

1 个回答

2

我想我明白这里发生了什么:

注意,你不能用ForeignKey对象来定义一个“组合”的外键约束,也就是说,不能在多个父子列之间建立这样的约束。要定义这种组合,必须使用ForeignKeyConstraint对象,并将其应用到表上。相关的ForeignKey对象会自动创建。

抱歉大家。谢谢你们的帮助!:D

编辑:这是我为需要的人提供的解决方案:

class Child(Base):

    __tablename__ = "childs"

    mid = Column(Integer(11), primary_key = True, autoincrement = False)
    cid = Column(Integer(11), primary_key = True)
    uid = Column(Integer(11), primary_key = True)

    __table_args__ = (ForeignKeyConstraint([cid, uid], [Parent.cid, Parent.uid]), {})

撰写回答