Writing to linked tables in a transaction

I recently had a use case at work (a LiteStar app) where I needed to write to two linked tables (see below) in a transaction in our PostgreSQL database. In the models for the two tables was included a foreign key relationship: from sqlalchemy import Column, String, DateTime, ForeignKey from sqlalchemy.orm import Mapped, relationship from typing import List # UUIDBase automatically generates a UUID for the primary key from advanced_alchemy.extensions.litestar import base class flows(base.UUIDBase): __tablename__ = 'flows' name: Column(String) date: Column(DateTime) files: Mapped[List["Files"]] = relationship( back_populates='flow', cascade='all, delete-orphan' ) class Files(base.UUIDBase): __tablename__ = 'files' file_name: Column(String) date: Column(DateTime) flow_id: Mapped[UUID] = mapped_column(ForeignKey('flows.id')) flow: Mapped["Flows"] = relationship(back_populates='files') My first - very naive approach was to include both writes in a single transaction (see next block). This kept failing because the foreign key from the first write (to the flows table) wasn’t available yet. The error that arose was that the ID wasn’t found, which took probably too long for me to figure out that it just wasn’t available yet. ...

October 21, 2025 · 2 min · Scott Chamberlain

Notes on FastAPI, LiteStar and HTMX

I recently wrote about Picking a web framework for a project at work. We’re moving from an R Shiny app to something else. We weren’t sure what that something else should be so I rebuilt the app (in part) in three different web frameworks (each in a different programming language): FastAPI (Python) Rails (Ruby) Svelte (JavaScript) I decided to go with FastAPI for many reasons - go read the post linked above. ...

October 9, 2025 · 6 min · Scott Chamberlain