2010-10-22 185 views
3

我試圖做到這一點:SQLAlchemy的:(通過關聯對象多對多)多重關係

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的繼承與我有關嗎?

謝謝!

回答

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

相關問題