gpt4 book ai didi

sqlalchemy:多重关系(通过关联对象实现多对多)

转载 作者:行者123 更新时间:2023-12-01 13:04:19 26 4
gpt4 key购买 nike

我正在尝试这样做:

class Foo(Base):
id = Column(Integer, primary_key=True)

class Bar(Foo):
id = Column(Integer, primary_key=True)

class FooBarAssociation(Base):
foo_id = Column(Integer, ForeignKey('foo_table.id'))
bar_id = Column(Integer, ForeignKey('bar_table.id'))

foo = relationship(Foo, backref=...)
bar = relationship(Bar, backref=...)

...但是我得到这样的错误:

Could not determine join condition between parent/child tables on relationship FooBarAssociation.foo.  Specify a 'primaryjoin' expression.  If this is a many-to-many relationship, 'secondaryjoin' is needed as well.

我试过在关系声明中指定 foreign_keys 和 primary_join-s,但都是徒劳。帮助?从 Foo 继承 Bar 是在搞乱我吗?

谢谢!

最佳答案

以下应该有效(正是错误告诉的内容:缺少 primaryjoin):

class FooBarAssociation(Base):
foo_id = Column(Integer, ForeignKey('foo_table.id'), primary_key = True, )
bar_id = Column(Integer, ForeignKey('bar_table.id'), ForeignKey('foo_table.id'), primary_key = True, )

foo = relationship(Foo, backref="bars", primaryjoin=(foo_id==Foo.id))
bar = relationship(Bar, backref="foos", primaryjoin=(bar_id==Bar.id))

如您所见,bar_id 列上有两个外键。由于继承,这可能是必需的,或者您可能会删除一个。但是,如果您不存储除多对多关系之外的任何其他信息,那么您可能会考虑 Association Proxy相反。

关于sqlalchemy:多重关系(通过关联对象实现多对多),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4001215/

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