Sqlalchemy:多对多关系错误
亲爱的大家,我正在学习在这个链接上描述的多对多关系。
#This is actually a VIEW
tb_mapping_uGroups_uProducts = Table( 'mapping_uGroups_uProducts', metadata,
Column('upID', Integer, ForeignKey('uProductsInfo.upID')),
Column('ugID', Integer, ForeignKey('uGroupsInfo.ugID'))
)
tb_uProducts = Table( 'uProductsInfo', metadata,
Column('upID', Integer, primary_key=True)
)
mapper( UnifiedProduct, tb_uProducts)
tb_uGroupsInfo = Table( 'uGroupsInfo', metadata,
Column('ugID', Integer, primary_key=True)
)
mapper( UnifiedGroup, tb_uGroupsInfo, properties={
'unifiedProducts': relation(UnifiedProduct, secondary=tb_mapping_uGroups_uProducts, backref="unifiedGroups")
})
这里面,uProduct和uGroup之间的关系是N:M。
当我运行以下代码时:
sess.query(UnifiedProduct).join(UnifiedGroup).distinct()[:10]
我遇到了一个错误:
sqlalchemy.exc.ArgumentError: Can't find any foreign key relationships between 'uProductsInfo' and 'uGroupsInfo'
我哪里做错了呢?
补充说明:我使用的是MyISAM,这个不支持外键。
1 个回答
2
在SQLAlchemy的结构中,外键定义的存在就足够了,它们在实际的表中并不是必须的。你的模型之间没有直接的外键关系,所以SQLAlchemy找不到它们。你需要明确指定要连接的关系:
sess.query(UnifiedProduct).join(UnifiedProduct.unifiedGroups).distinct()[:10]