python module_error ai_generated true

sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper[User], expression 'Post' failed to locate a name ('Post'). If this is a class name, consider adding this relationship() to the class after both dependent classes have been defined.

ID: python/sqlalchemy-circular-import-models

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-02-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.0.x active

Root Cause

Circular imports between model modules cause one model class to be undefined when the other's mapper is configured.

generic

中文

模型模块之间的循环导入导致在配置映射器时,某个模型类尚未定义。

Workarounds

  1. 90% success
    Use string-based relationship references: class User(Base): posts = relationship('Post', back_populates='user') - and ensure Post is defined later in the same module or imported lazily.
  2. 85% success
    Use the 'late-binding' pattern: define relationships in a separate configure_mappers() call after all models are imported: from sqlalchemy.orm import configure_mappers; configure_mappers()

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Top-level imports still trigger the same circular dependency; the classes are not yet defined at import time.

  2. 80% fail

    If the __init__.py imports both modules, it still hits the circular reference during module initialization.