What is the difference between
class Base(DeclarativeBase):
pass
vs
Base = DeclarativeBase()
I am following the SQLAlchemy Tutorial for declaring mapped classes 
<https://docs.sqlalchemy.org/en/20/tutorial/metadata.html> 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))
fullname:Mapped[Optional[str]]

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)
email_address:Mapped[str]
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})"

Base.metadata.create_all(bind=engine)

-- 
SQLAlchemy - 
The Python SQL Toolkit and Object Relational Mapper

http://www.sqlalchemy.org/

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+unsubscr...@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 via email to