Sqlalchemy: multiple relationships (many of many through association)

I am trying to do this:

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=...)

... but I get errors like this:

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.

I tried specifying foreign_keys and primary_join-s in relationship declarations, but all this is in vain. Help? Is the inheritance bar from foo messing with me?

thank!

+3
source share
1 answer

The following should work (exactly what the error says: missing 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 . - , . - "--", "-" .

+4

Source: https://habr.com/ru/post/1771001/


All Articles