【问题标题】:sqlalchemy: multiple relationships (many to many via association object)sqlalchemy:多重关系(通过关联对象多对多)
【发布时间】:2010-10-27 21:41:15
【问题描述】:

我正在尝试这样做:

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 是不是惹到我了?

谢谢!

【问题讨论】:

    标签: sqlalchemy


    【解决方案1】:

    以下应该可以工作(确切地说是错误:缺少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

    【讨论】:

      猜你喜欢
      • 2015-03-16
      • 1970-01-01
      • 2017-11-22
      • 1970-01-01
      • 2018-11-24
      • 1970-01-01
      • 2011-11-10
      • 1970-01-01
      相关资源
      最近更新 更多