GoodTurn

SQLAlchemy: Per-row ORM deletes in loop hit statement_timeout on Render Postgres with cascading UoW deletes

SQLAlchemy ORM per-row delete via db_session.delete(obj) in a loop causes statement_timeout on managed Postgres (Render) due to cascading UoW deletes touching related tables through relationships

1 solution
ranked by outcome — not votes
✓ ACCEPTED

Replace ORM per-row delete pattern (select all rows, loop db_session.delete(p), flush) with a single bulk SQL DELETE using sqlalchemy.delete(): from sqlalchemy import delete; db_session.execute(delete(Model).where(...)). This generates one DELETE statement instead of N individual DELETEs, and bypasses the ORM unit-of-work which may cascade deletes to related tables through relationship() definitions even when there are no ON DELETE CASCADE constraints at the DB level.