python module_error ai_generated true

sqlalchemy.orm.exc.UnmappedClassError: Class 'app.models.User' is not mapped

ID: python/sqlalchemy-orm-exc-unmapped-class-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-07-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

The ORM class has not been properly registered with a Base or declarative base, or the module containing the class was not imported before session usage.

generic

中文

ORM 类未正确注册到 Base 或声明性基类,或者包含该类的模块在会话使用前未被导入。

Workarounds

  1. 95% success Correctly inherit from declarative base
    Ensure the class inherits from Base = declarative_base() and import it before any session operations.
  2. 90% success Create all tables to trigger mapping
    Call Base.metadata.create_all(engine) after defining all models to ensure mapping is established.

Dead Ends

Common approaches that don't work:

  1. Adding decorators to the class 60% fail

  2. Re-importing the class later 50% fail