ImportError: cannot import name 'declarative_base' from 'sqlalchemy.ext.declarative'
Fixes ImportError: cannot import name 'declarative_base' from 'sqlalchemy.ext.declarative' Use when SQLAlchemy 2.x and old `sqlalchemy.ext.declarative` imports Not for: SQLAlchemy 1.4 (both import paths work there)
How to fix ImportError: cannot import name 'declarative_base' from 'sqlalchemy.ext.declarative'
SQLAlchemy 2.0 removed sqlalchemy.ext.declarative.declarative_base. Import it from sqlalchemy.orm instead: from sqlalchemy.orm import declarative_base. (Or go full 2.0 style with class Base(DeclarativeBase).) One-line change, same behavior.
The exact error
ImportError: cannot import name 'declarative_base' from 'sqlalchemy.ext.declarative'Fix it
- Replace
from sqlalchemy.ext.declarative import declarative_basewithfrom sqlalchemy.orm import declarative_base.
Expected: import works on SQLAlchemy 2.x
- Run your test suite and migrations.
Expected: models load, migrations run
- Optional modernize:
from sqlalchemy.orm import DeclarativeBaseandclass Base(DeclarativeBase): pass.
Expected: 2.0-native style
When this applies
SQLAlchemy 2.x and old sqlalchemy.ext.declarative imports
When this does NOT apply
SQLAlchemy 1.4 (both import paths work there)
Versions
SQLAlchemy >= 2.0
Why it happens
1.4 deprecated the ext.declarative location; 2.0 removed it.
Edge cases
Some old tutorials also use sqlalchemy.ext.declarative.api; same fix.
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.