2013-03-20 46 views
1

SQLAlchemy的關係錯誤所以我在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: Could not determine join condition between parent/child tables on relationship Parent.childs_rel - there are multiple foreign key paths linking the tables. Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference to the parent table.

我試圖指定childs_rel「foreign_keys」,但它最高審計機關沒有外鍵在父類中,這是真的......必須在孩子的類中指定,但根據SQLAlchemy的ORM文檔,關係在「一對多」相關中的「一個」中定義...

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

您認爲在這裏發生了什麼? Thx很多!

回答

2

我想我知道這裏發生了什麼:

Note that you cannot define a 「composite」 foreign key constraint, that is a constraint between a grouping of multiple parent/child columns, using ForeignKey objects. To define this grouping, the ForeignKeyConstraint object must be used, and applied to the Table. The associated ForeignKey objects are created automatically.

對不起球員。無論如何,Thx! :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]), {}) 
相關問題