How to auto-generate a primary key column in sqlmodel

In order to auto-generate a primary key column in SQLModel, you need to add an Optional[int] column (so you don’t have to explicitly specify a value) with default=None and primary_key=True.

id: Optional[int] = Field(default=None, primary_key=True)

Full example


from sqlmodel import Field, SQLModel, create_engine, Session, select

class Hero(SQLModel, table=True):
    # The "id" column with autoincrement is our primary key
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str
    secret_name: str