Skip to content Skip to sidebar Skip to footer

Sqlalchemy Joins With Composite Foreign Keys (with Flask-sqlalchemy)

I'm trying to understand how to do joins with composite foreign keys on SQLAlchemy and my attempts to do this are failing. I have the following model classes on my toy model (I'm

Solution 1:

Your code has few typos, correcting which will make the whole code work.

Define properly the ForeignKeyConstraint:

  • it is not to just define it, you have to add it to __table_args__
  • definition of columns and refcolumns parameters is reversed (see documentation)
  • names of the columns must be names in the database, and not name of ORM attributes

as shown in the following code:

class Zabumba(db.Model):
    __tablename__ = 'zabumba'

    __table_args__ = (
        db.ForeignKeyConstraint(
            ['usuario', 'perfil'],
            ['asset.usuario', 'asset.perfil'],
        ),
    )

construct properly the query by having both classes in the query clause:

for asset, zabumba in db.session.query(Asset, Zabumba).join(Zabumba).all():
        print"{:25}\t<---->\t{:25}".format(asset, zabumba)

Post a Comment for "Sqlalchemy Joins With Composite Foreign Keys (with Flask-sqlalchemy)"