我正在尝试这样做:
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的遗产是否与我混在一起?
谢谢!
答案 0 :(得分:4)
以下应该可以正常工作(正是错误告诉我的内容:缺少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。