Choose, and choose quickly: Optimising ModelChoiceField
summary
Django REST Framework browseable form, django-filter forms and admin list_editable slow when ModelChoiceField fetches related rows: a suburb dataset with 17,871 rows triggers ~1,002 SQL queries (DRF cutoff) or ~17,871 queries (django-filter) and the admin can hang. Solutions: use select_related / prefetch_related to cut queries (1,002 β 4; 17,871 β 6), compute choices once per formset to don't repeat work (35 β 11), or precompute and cache choices to do the work early (down to ~5 queries).
AI-written summary Β· about
chapters (12)
- 0:00Introduction and setup
- 2:52What is ModelChoiceField
- 6:43Example one: DRF serializer form
- 7:46Example two: Django filter form
- 9:11Example three: Django admin list editable
- 11:38Strategy one: Do less work
- 15:48Strategy two: Don't repeat work
- 18:54Strategy three: Do work early
- 20:15Summary and takeaways
- 21:40Q&A: Automatic prefetching
- 24:30Q&A: Only queries optimization
- 26:46Q&A: Handling large choice lists
