-
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 DescriptionFirst 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()
@app.on_event("startup")
def on_startup():
print("startup")
# create_db_and_tables() Am I missing something that is causing this behavior? Operating SystemLinux Operating System DetailsNo response SQLModel Version0.0.6 Python Version3.10.4 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 16 comments
-
Similar problem when trying to set a timing decorator. Must be something general in the context of wrapper functions or decorators respectively. This is apperently not limited to SQLModel, since I'm not using SQLModel but declarative_base from SQLAlchemy. |
Beta Was this translation helpful? Give feedback.
-
I cannot reproduce this error. Works fine for me. What version of SQLAlchemy is installed in the environment where you experienced this error? Or has this issue been resolved? |
Beta Was this translation helpful? Give feedback.
-
I had the same problem. |
Beta Was this translation helpful? Give feedback.
-
I have the same problem with even less code:
The same ERROR pops when I run the program with But everything looks OK if I run it with Here is pipenv graph, if it helps:
|
Beta Was this translation helpful? Give feedback.
-
The problem is because from sqlmodel import Field, SQLModel
print("here")
class Hero(SQLModel, table=True): You can solve this by calling app = FastAPI()
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8001) Or, by separating the code into two files:
import uvicorn
if __name__ == "__main__":
uvicorn.run("app:app", host="0.0.0.0", port=8001)
from typing import Optional
import uvicorn as uvicorn
from fastapi import FastAPI
from sqlmodel import Field, SQLModel
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
app = FastAPI() |
Beta Was this translation helpful? Give feedback.
-
meirdev thanks issue resolved |
Beta Was this translation helpful? Give feedback.
-
Thanks |
Beta Was this translation helpful? Give feedback.
-
I was also getting this error when I imported the In the end I figured out that I was importing from |
Beta Was this translation helpful? Give feedback.
-
Similar problem with streamlit |
Beta Was this translation helpful? Give feedback.
-
this work for me. try adding this.
|
Beta Was this translation helpful? Give feedback.
-
When the import path is incorrect, I encountered the following error: # occurred error
from foo.bar import Something
# worked out well
from src.foo.bar import Something |
Beta Was this translation helpful? Give feedback.
-
I'm having the problem even without FastAPI:
By running Python version: |
Beta Was this translation helpful? Give feedback.
-
Works with this edit to the
|
Beta Was this translation helpful? Give feedback.
-
If you encounter such error, it might be because the file with models gets executed twice. Add a debug print on top of the file to check it. print("----") As mentioned above the cause of such behavior might be uvicorn. In my case it was relative imports. |
Beta Was this translation helpful? Give feedback.
-
Thanks, that worked for me! |
Beta Was this translation helpful? Give feedback.
-
this inspired me to solve my problem, I was importing the import sys
import traceback
print(f"app.models loaded as: {__name__}, id: {id(sys.modules[__name__])}")
traceback.print_stack()
``` |
Beta Was this translation helpful? Give feedback.
The problem is because
uvicorn
is loading the file again, you can see this by addingprint
:You can solve this by calling
app
directly:Or, by separating the code into two files:
main.py
:app.py
: