What's the difference between `select_related()` and `prefetch_related()`?


The difference between Django selectrelated and prefetchrelated, explained by the SQL each one produces. selectrelated adds a JOIN so related columns arrive in the same query and Django builds both objects from one row, which works only when the relation contributes at most one row per result: a forward ForeignKey, a OneToOneField, or a reverse one-to-one. prefetchrelated instead issues a second query using WHERE id IN and matches the results onto parent instances in Python, which is what makes it correct for reverse foreign keys and ManyToManyField, where a JOIN would multiply every parent row by its children and break LIMIT. Shows the N+1 pattern costing four queries for three rows, the same loop collapsing to one JOINed query, and a reverse relation going from four queries to two, with select_related raising FieldError when asked for a multi-valued relation. Includes runnable Django code and real output, plus Prefetch objects, chained lookups, nullable joins, and only/defer interactions.

Comments

No comments yet. Be the first to share your thoughts.
Intermediate
0.0 (0)

Author

Software engineer and the creator of the Bytestark learning platform