-
First Check
Commit to Help
Example Codeimport os
from typing import List
from fastapi import FastAPI
from pydantic import BaseModel
from sqlalchemy import create_engine, select
from sqlmodel import Field, SQLModel, Session
from dotenv import load_dotenv
import uvicorn
load_dotenv()
app = FastAPI()
class CategoryBase(SQLModel):
name: str = Field(nullable=False, max_length=255)
position: int = Field(nullable=False, default=0)
class Category(CategoryBase, table=True):
__tablename__ = "category"
id: int | None = Field(primary_key=True)
sql_engine = create_engine(url=os.getenv("DATABASE_URL"), echo=True)
def get_session():
return Session(bind=sql_engine)
class CategoryModel(BaseModel):
id: int
name: str
position: int
@app.get("/", response_model=List[CategoryModel])
async def get_categories():
with get_session() as session:
categories = session.exec(select(Category).order_by(Category.position)).all()
return categories
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000) DescriptionWhen running this app, I get the following error:
However, the data is correctly loaded as seen during debugging, or even when looking at the error message. When omitting the
Strangely, when using the following calls to either # working fine with query
@app.get("/", response_model=List[CategoryModel])
async def get_categories():
with get_session() as session:
categories = session.query(Category).order_by(Category.position).all()
return categories # working fine with execute
@app.get("/", response_model=List[CategoryModel])
async def get_categories():
with get_session() as session:
categories = session.execute(
select(Category).order_by(Category.position)
).scalars().all()
return categories Both Operating SystemLinux, Windows Operating System DetailsTried both Windows and WSL Ubuntu SQLModel Version0.0.24 Python Version3.13.1 Additional ContextI'm using Postgresql17 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The problem was that I imported the wrong Wrong Correct |
Beta Was this translation helpful? Give feedback.
The problem was that I imported the wrong
select
function.Wrong
from sqlalchemy import select
Correct
from sqlmodel import select