Python & FastAPI•Part 5: ORMs, Databases & Background Workers (56 - 65)
SQLAlchemy 2.0 vs Legacy 1.x:
In Simple Words:
SQLAlchemy 2.0 unifies the Core and ORM syntax around explicit select() statements and provides full native support for type hints and async sessions.
python
from sqlalchemy import select
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase): pass
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
# Modern SQLAlchemy 2.0 query syntax:
stmt = select(User).where(User.name == "Alice")