SQLAlchemy joins with composite foreign keys (with flask-sqlalchemy)

后端 未结 1 547
情书的邮戳
情书的邮戳 2021-01-05 08:57

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

相关标签:
1条回答
  • 2021-01-05 09:08

    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)
    
    0 讨论(0)
提交回复
热议问题