sqlalchemyfastapisqlmodel

Changing SQLModel instance does not affect database table


i am pretty new to SQLModel so bare with me.

I am following sqlmodel tutorial on their website and have created my own SQLModel subclass:

class Vehicle(SQLModel, table=True):
   __tablename__ = "vehicle"

   id: int = Field(primary_key=True)
   url: str =  Field(unique=True)
   vehicle_name: str | None = Field(default=None, nullable=True)

Then i create engine and apply this model to database:

url = "< my database url >"
engine = sqlmodel.create_engine(url)
Vehicle.metadata.create_all(engine)

First time i run this code everything works great. The table is created, all defined columns are there. But if i change some property on Vehicle model and run this code again, I don't see any change on table.

Why is this happening and how do I fix it? If I change something on Vehicle model, I want that change to be detected and automatically migrated to database.


Solution

  • SQLModel uses the SQLAlchemy library and builds on it. The create_all() function is importet directly from SQLAlchemy. Here is the relevant documentation:

    Create all tables stored in this metadata. Conditional by default, will not attempt to recreate tables already present in the target database.

    This means that once created, SQLModel will not attempt to change the schema of your database tables. To manage schema migrations, you can have a look at a tool like alembic, which is designed to work with SQLAlchemy. There are some good resources available online on how to use alembic with SQLModel (this one for example).