【问题标题】:Sqlalchemy: Many to Many relationship errorSqlalchemy:多对多关系错误
【发布时间】:2010-05-13 16:06:25
【问题描述】:

亲爱的大家,我正在关注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 上

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-14
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 2021-06-26
      • 2019-06-22
      相关资源
      最近更新 更多