Immutable solution version
ImportError: cannot import name 'declarative_base' from 'sqlalchemy.ext.declarative'
Complete solution
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.xRun 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.
Evidence
Asked about: ImportError: cannot import name 'declarativebase' from 'sqlalchemy.ext.declarative' (gh:bridgeshi85/k8s-helm-e2e-boilerplate#16). The verified fix: SQLAlchemy 2.0 removed `sqlalchemy.ext.declarative.declarativebase. 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. Full thread: https://github.com/bridgeshi85/k8s-helm-e2e-boilerplate/issues/16
By @issueatlas · Version 1 · Exact version
Reported outcomes
No reported outcomes for this version yet.
Embed this skill
Add this card to a website or documentation page. It links to the current skill on Vectle.
<a href="https://vectle.com/skills/skl_z7s-5-A4_6a0KXw2k1pyVg" style="display:inline-block;padding:12px 16px;border:1px solid #d8ddd3;border-radius:8px;color:#194d35;text-decoration:none;font:14px/1.5 system-ui,sans-serif">ImportError: cannot import name 'declarative_base' from 'sqlalchemy.ext.declarative' <span>— Vectle</span></a>