diff --git a/crud.py b/crud.py index 881d50c..f5e1f39 100644 --- a/crud.py +++ b/crud.py @@ -4,7 +4,7 @@ from sqlalchemy import DECIMAL, cast import models, schemas def get_items(db: Session) -> list[models.Item]: - return db.query(models.Item).order_by(models.Item.type, cast(models.Item.id, DECIMAL)) + return db.query(models.Item).all() def put_item(db: Session, id: str, item: schemas.Item): diff --git a/main.py b/main.py index c52f809..166e0cf 100644 --- a/main.py +++ b/main.py @@ -3,6 +3,7 @@ from fastapi.staticfiles import StaticFiles from sqlalchemy import event from sqlalchemy.orm import Session from sqlalchemy.engine import Engine +import re import crud from database import SessionLocal, engine @@ -29,7 +30,10 @@ def _set_sqlite_pragma(conn, _): @app.get("/api/items", response_model=dict[str, Item]) async def list_items(db: Session = Depends(get_db)): + # sort by type, id (natural) + natsort = lambda s: (s.type, [int(t) if t.isdigit() else t.lower() for t in re.split('(\d+)', s.id)]) items = crud.get_items(db) + items = sorted(items, key=natsort) return {i.id:i for i in items}