First Check
Commit to Help
Example Code
# using code from - https://sqlmodel.tiangolo.com/tutorial/fastapi/multiple-models/?h=hero#the-herocreate-data-model
from typing import List, Optional
from fastapi import FastAPI
from sqlmodel import Field, Session, SQLModel, create_engine, select
class HeroBase(SQLModel):
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
class Hero(HeroBase, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
class HeroCreate(HeroBase):
pass
class HeroRead(HeroBase):
id: int
engine = create_engine(
"postgresql+psycopg2://postgres:postgres@localhost/testing", echo=True
)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
app = FastAPI()
@app.on_event("startup")
def on_startup():
create_db_and_tables()
@app.post("/heroes/", response_model=HeroRead)
def create_hero(hero: HeroCreate):
with Session(engine) as session:
db_hero = Hero.from_orm(hero)
session.add(db_hero)
session.commit()
session.refresh(db_hero)
return db_hero
@app.get("/heroes/", response_model=List[HeroRead])
def read_heroes():
with Session(engine) as session:
heroes = session.exec(select(Hero)).all()
return heroes
Description
First attempt fails with.
sqlalchemy.exc.InvalidRequestError: Table 'hero' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.
Adding this fixes this problem, however reading various sites this is not recommended?
class Hero(HeroBase, table=True):
__table_args__ = {"extend_existing": True} # < new
id: Optional[int] = Field(default=None, primary_key=True)
Second attempt fails with.
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.DuplicateTable) relation "ix_hero_name" already exists
[SQL: CREATE INDEX ix_hero_name ON hero (name)]
Moving the create_db_and_tables() out of the functions startup event fixes this problem and everything works as expected
create_db_and_tables()
@app.on_event("startup")
def on_startup():
print("startup")
# create_db_and_tables()
Am I missing something that is causing this behavior?
Operating System
Linux
Operating System Details
No response
SQLModel Version
0.0.6
Python Version
3.10.4
Additional Context
No response
First Check
Commit to Help
Example Code
Description
First attempt fails with.
Adding this fixes this problem, however reading various sites this is not recommended?
Second attempt fails with.
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.DuplicateTable) relation "ix_hero_name" already exists [SQL: CREATE INDEX ix_hero_name ON hero (name)]Moving the
create_db_and_tables()out of the functions startup event fixes this problem and everything works as expectedAm I missing something that is causing this behavior?
Operating System
Linux
Operating System Details
No response
SQLModel Version
0.0.6
Python Version
3.10.4
Additional Context
No response