1

所以我在 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的类中没有外键,这是真的......必须在child的类中指定,但根据SQLAlchemy的ORM doc,关系定义在“ “一对多”关系中的一个”...

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

你认为这里发生了什么?多谢!

4

1 回答 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]), {})
于 2013-03-21T09:45:47.207 回答