The N+1 problem

The N+1 problem occurs when a query loads N objects and then runs one extra query for each of them to access a relationship, N+1 queries in total. It severely degrades performance. In Django, select_related (a join for single-valued relationships) and prefetch_related (a batched query for multi-valued relationships) fix it.

Example

Post.objects.select_related('author').prefetch_related('tags')

Related concepts

The whole glossary