Member-only story
Getting Started with SQLAlchemy ORM — Creating Tables (2/5)
Unlike Core, we will not use metadata, but declarative_base
which will have metadata. When we access metadata, it works the same way as in Core.
Declarative Base
We start by creating a Base
class that we will use for defining tables.
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
pass
Table
Now we create a class that will inherit from the Base
class. Using __tablename__
, we define how the table will be named in the database.
Then we define the fields on the class. If we want the column in the database to have the same name as the field, we don't need to specify the column name in Column
as in Core. The rest in Column
remains the same as in Core.
from sqlalchemy import Column, Integer, Text
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
first_name = Column(Text, nullable=True)
last_name = Column(Text, nullable=True)
If we want to create tables, we can use the metadata on the Base
class.
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
It is also possible to create and delete classes one by one. In such a case, we do not use metadata on the Base, but directly use the class (User) and call __table__.create/drop
on it.
User.__table__.create(engine, checkfirst=True)
User.__table__.drop(engine, checkfirst=True)