I have an SQLAlchemy model like the one below, and at first it didn’t work (problems with the join, and then expecting a scalar instead of a list). I “fixed” it in the included version, but I really can’t understand why it behaved like that.
At first I expected that with those ForeignKeys the Sizes.items relationship() shouldn’t need an explicit primaryjoin, and when I added it SA started expecting a scalar and I had to explicitly specify uselist=True.
Why doesn’t the relationship automatically detect one or both those things?
class Category(Base):
__tablename__ = 'categories'
pk = Column(String(6), primary_key=True)
class Item(Base):
__tablename__ = 'items'
pk = Column(String(6), primary_key=True)
category_pk = Column(String(6), ForeignKey('categories.pk') )
size = Column(Integer(), nullable=False)
category = relationship('Category', backref=backref('items'))
class Sizes(Base):
__tablename__ = 'sizes'
category_pk = Column(String(6), ForeignKey('categories.pk'),
ForeignKey('items.category_pk'), primary_key=True )
size = Column(Integer(), ForeignKey('items.size'), primary_key=True )
category = relationship('Category', backref=backref('sizes'))
items = relationship('Item',
uselist=True,
primaryjoin="and_(Sizes.category_pk==Item.category_pk, Sizes.size==Item.size)" )
I believe what is happening is that you have two foreign keys, not a single FK on two columns. It works a bit different the primary_key=True where you can do that.
Try something like: