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

こ雲淡風輕ζ 提交于 2019-11-30 20:10:26

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!