01The problem
The reports covered point expirations and reward redemptions. They were written the straightforward way: fetch rows, loop over them in Python, look up related data as you go, add things up. That's fine with a few hundred rows. With a real programme's data it means many round trips to the database and a lot of Python doing what the database does better.
02The decision
Push the work down to the database and let Python receive results, not raw material:
- Queryset annotations to compute per-row values in SQL instead of in a loop.
Coalesceto handle missing values inside the query, so Python doesn't have to patch nulls row by row.values()to fetch only the columns the report uses rather than full model instances.select_relatedto join related tables in one query instead of one lookup per row.
I applied the same approach to each generator in turn and measured each one.
03Result
| Report | Before | After | Speedup |
|---|---|---|---|
| Expiration journal | 41.91s | 0.22s | ~190x |
| Expiration log | 7.10s | 0.12s | ~57x |
| Redemption details | 5.73s | 0.11s | ~53x |
This isn't Android work, and that's why it's here. The habit is the same on either platform: find where the work actually happens, measure it, and move it to the layer that's built for it.