Big O No: Django ORM runtime complexity and how to avoid it using LATERAL JOINS
summary
Claims that Django can avoid N+1 and even O(n^2) query explosions by using LATERAL JOINs and correlated subqueries to run per-row aggregations and embed related rows as JSON. Demonstrates use of json_agg/json_build_array to bundle comments and a library, django-include drop-in replacement, to rehydrate models. Shows raw-SQL reduced hundreds of queries to one and shaved a couple seconds off an endpoint, but benchmarks report parity with prefetch_related in many cases and worse performance on CockroachDB for large top-level loads.
AI-written summary · about
chapters (5)
- 0:00Start
- 4:56SQL queries can get real slow real fast
- 8:07Scenario 2: Many related rows
- 13:45Benchmarks (Postgres)
- 14:42Benchmarks (CockroachDB)
related talks
29mMaking smarter queries with advanced ORM resources
30mLeave Your Inhibitions at the Database Connection
01h 04mInside the ORM
27mDjango - Customise your SQL
25mBuilding effective Django queries with expressions
21mDjango and PostgreSQL: An Even-Closer Union
27mFinding and fixing an N+1 problem in the Django docs
23mDjango with PostgreSQL superpowers
