简体   繁体   中英

SQLAlchemy relationship error with one-to-many rel

So I have this one-to-many relationship in 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")

and

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)
    ...

I can create this database, but when I try to manipulate it I get this error:

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.

I have tried to specify 'foreign_keys' in childs_rel but it sais there is no foreign key in Parent's class, and that is true... that has to be specified in child's class but according to SQLAlchemy's ORM doc, relationship is defined in the "one" in the "one-to-many" rel...

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

What do you think that is happening here? Thx a lot!

I think I know what is happening here:

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.

Sorry guys. Thx anyway! :D

EDIT: Here is my solution for those who need it:

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]), {})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM