【问题标题】:SQLAlchemy relationship error with one-to-many relSQLAlchemy关系错误与一对多rel
【发布时间】:2013-03-10 00:32:12
【问题描述】:

所以我在 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 文档,定义了关系在“一对多”关系中的“一”中...

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

您认为这里发生了什么? 非常感谢!

【问题讨论】:

    标签: python mysql sqlalchemy one-to-many


    【解决方案1】:

    我想我知道这里发生了什么:

    请注意,您不能定义“复合”外键约束,即 是多个父/子列的分组之间的约束, 使用 ForeignKey 对象。为了定义这个分组, 必须使用 ForeignKeyConstraint 对象,并将其应用于 Table。 关联的 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]), {})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-14
      • 1970-01-01
      • 2012-06-14
      • 2020-09-18
      • 1970-01-01
      • 2016-06-15
      • 2021-08-31
      • 1970-01-01
      相关资源
      最近更新 更多