亲爱的大家,我正在关注http://www.sqlalchemy.org/docs/mappers.html#many-to-many
中描述的多对多关系#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上,不支持forigen键
答案 0 :(得分:2)
SQLAlchemy架构中存在外键定义就足够了,它们在实际表中不是必需的。您的模型之间没有直接外部关系,因此SQLAlchemy无法找到它们。指定要明确加入的 relation :
sess.query(UnifiedProduct).join(UnifiedProduct.unifiedGroups).distinct()[:10]