Posts
read more
Avoiding ORM Traps and the N+1 Problem in Python
Introduction
Python’s ORMs — SQLAlchemy and the Django ORM — are a joy to write and dangerously easy to make slow. A loop over a queryset that reads one related field can silently fire hundreds of queries. It looks fine in development and falls over on real data.
This post covers the ORM traps Python teams hit most, starting with the N+1 query problem, in both SQLAlchemy and Django.
The N+1 Problem
You load authors and print each author’s book count: