{
  "id": "python/sqlalchemy-circular-import-models",
  "signature": "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.",
  "signature_zh": "sqlalchemy.exc.InvalidRequestError: 初始化映射器 Mapper[User] 时，表达式 'Post' 无法定位名称 ('Post')。如果这是一个类名，请考虑在两个依赖类都定义后，将此 relationship() 添加到类中。",
  "regex": "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\\.",
  "domain": "python",
  "category": "module_error",
  "subcategory": null,
  "root_cause": "Circular imports between model modules cause one model class to be undefined when the other's mapper is configured.",
  "root_cause_type": "generic",
  "root_cause_zh": "模型模块之间的循环导入导致在配置映射器时，某个模型类尚未定义。",
  "versions": [
    {
      "version": "2.0.x",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    }
  ],
  "os_specific": {},
  "dead_ends": [
    {
      "action": "",
      "why_fails": "Top-level imports still trigger the same circular dependency; the classes are not yet defined at import time.",
      "fail_rate": 0.9,
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "why_fails": "If the __init__.py imports both modules, it still hits the circular reference during module initialization.",
      "fail_rate": 0.8,
      "condition": "",
      "sources": []
    }
  ],
  "workarounds": [
    {
      "action": "",
      "success_rate": 0.9,
      "how": "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.",
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "success_rate": 0.85,
      "how": "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()",
      "condition": "",
      "sources": []
    }
  ],
  "workarounds_zh": [],
  "transition_graph": {
    "leads_to": [],
    "preceded_by": [],
    "frequently_confused_with": []
  },
  "official_doc_url": null,
  "official_doc_section": null,
  "error_code": null,
  "verification_tier": "ai_generated",
  "confidence": 0.88,
  "fix_success_rate": 0.8,
  "resolvable": "true",
  "first_seen": "2024-02-10",
  "last_confirmed": "2025-01-01",
  "last_updated": "2025-01-01",
  "evidence_count": 0,
  "tags": [],
  "locale": "en",
  "aliases": []
}