python config_error ai_generated true

一个或多个映射器初始化失败 - 无法继续操作。原始异常:对于关系 'User.roles',辅助表 'user_roles' 与父表和子表不在同一个 MetaData 中。

sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with the operation. Original exception was: For relationship 'User.roles', the secondary table 'user_roles' is not in the same MetaData as the parent and child tables.

ID: python/sqlalchemy-many-to-many-relationship-config

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2024-08-09首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

多对多关系中使用的关联表使用不同的 MetaData 实例定义或未正确共享。

English

The association table used in a many-to-many relationship is defined with a different MetaData instance or not properly shared.

generic

解决方案

  1. 95% 成功率
    from sqlalchemy import Table, Column, ForeignKey
    from sqlalchemy.ext.declarative import declarative_base
    Base = declarative_base()
    user_roles = Table('user_roles', Base.metadata,
        Column('user_id', ForeignKey('users.id')),
        Column('role_id', ForeignKey('roles.id'))
    )
    class User(Base):
        __tablename__ = 'users'
        roles = relationship('Role', secondary=user_roles)

无效尝试

常见但无效的做法:

  1. 60% 失败

    Causes table redefinition and still may not share MetaData.

  2. 50% 失败

    SQLAlchemy requires consistent metadata for relationships.