Sqlalchemy:多对多关系

2024-09-30 06:15:12 发布

您现在位置:Python中文网/ 问答频道 /正文

亲爱的各位,我正在关注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

当我运行以下命令时

^{pr2}$

我得到了一个错误:

sqlalchemy.exc.ArgumentError: Can't find any foreign key relationships between 'uProductsInfo' and 'uGroupsInfo'

我做错什么了?在

编辑:我在MyISAM上,它不支持forigen键


Tags: keysqlalchemytablecolumnintegertbmappingmany
1条回答
网友
1楼 · 发布于 2024-09-30 06:15:12

SQLAlchemy模式中存在外键定义就足够了,它们在实际表中不是必需的。您的模型之间没有直接的外部关系,因此SQLAlchemy无法找到它们。指定要显式加入的关系

sess.query(UnifiedProduct).join(UnifiedProduct.unifiedGroups).distinct()[:10]

相关问题 更多 >

    热门问题