Difference b/w creating a DeclarativeBase class vs assigning DeclarativeBase()

Skip to first unread message

satya dev

Oct 10, 2023, 3:12:50 AM10/10/23
to sqlalchemy
What is the difference between
class Base(DeclarativeBase):
Base = DeclarativeBase()
I am following the SQLAlchemy Tutorial for declaring mapped classes when I inherit the Base class I can access the metadata and create my tables but when I assign it to Base and try to create the tables it throws an error saying
class User(Base):
TypeError: DeclarativeBase() takes no arguments

Code for reference:
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
from sqlalchemy import Integer, String, ForeignKey, MetaData, create_engine
from typing import List, Optional

engine = create_engine("postgresql://db_user:db_pw@localhost:5432/alembic_learning")
# class Base(DeclarativeBase):
# pass

Base = DeclarativeBase()

class User(Base):
__tablename__ = "users"

id: Mapped[int] = mapped_column(primary_key=True)
name:Mapped[str] = mapped_column(String(30))

addresses:Mapped[List["Address"]] = relationship(back_populates="user")

def __repr__(self) -> str:
return f"User(id={self.id!r}, name={self.name!r}, fullname={self.fullname!r})"
class Address(Base):
__tablename__ = "address"

id:Mapped[int] = mapped_column(primary_key=True)
user_id = mapped_column(ForeignKey("users.id"))

user:Mapped[User] = relationship(back_populates="addresses")

def __repr__(self)-> str:
return f"Address(id={self.id!r}, email_address={self.email_address})"


Simon King

Oct 10, 2023, 9:02:12 AM10/10/23
to sqlal...@googlegroups.com
I don't think this code was ever correct:

    Base = DeclarativeBase()

Before SQLAlchemy 2.0, there was a declarative_base() function that was used in the same way:

    from sqlalchemy.ext.declarative import declarative_base

    Base = declarative_base()

...but in SQLAlchemy 2.0, the preferred form is:

    from sqlalchemy.orm import DeclarativeBase

    class Base(DeclarativeBase):

The new approach works better with type-analysis tools like mypy.

Hope that helps,


SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description.
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/5b7821d7-ef3e-4b49-ae5c-880851b5ab43n%40googlegroups.com.
Reply all
Reply to author
0 new messages