gpt4 book ai didi

python - 具有一对多关系的 SQLAlchemy 关系错误

转载 作者:行者123 更新时间:2023-11-29 06:50:49 25 4
gpt4 key购买 nike

所以我在 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

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

最佳答案

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

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.

对不起各位。无论如何,谢谢! :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]), {})

关于python - 具有一对多关系的 SQLAlchemy 关系错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15531593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com