Skip to content

Commit 27fa551

Browse files
committed
Add documentation on avoiding N+1 queries using select_related/prefetch_related
1 parent 577bb3c commit 27fa551

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

docs/api-guide/generic-views.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,39 @@ For example:
102102

103103
---
104104

105+
### Avoiding N+1 Queries
106+
107+
When listing objects (e.g. using `ListAPIView` or `ModelViewSet`), serializers may trigger an N+1 query pattern if related objects are accessed individually for each item.
108+
109+
To prevent this, optimize the queryset in `get_queryset()` using `select_related()` and `prefetch_related()` depending on the type of relationship.
110+
111+
**For ForeignKey and OneToOneField**:
112+
113+
Use `select_related()` to fetch related objects in the same query:
114+
115+
def get_queryset(self):
116+
return Order.objects.select_related("customer", "billing_address")
117+
118+
**For reverse and many-to-many relationships**:
119+
120+
Use `prefetch_related()` to efficiently load collections of related objects:
121+
122+
def get_queryset(self):
123+
return Book.objects.prefetch_related("categories", "reviews__user")
124+
125+
**Combining both**:
126+
127+
def get_queryset(self):
128+
return (
129+
Order.objects
130+
.select_related("customer")
131+
.prefetch_related("items__product")
132+
)
133+
134+
These optimizations reduce redundant database access and improve list view performance.
135+
136+
---
137+
105138
#### `get_object(self)`
106139

107140
Returns an object instance that should be used for detail views. Defaults to using the `lookup_field` parameter to filter the base queryset.

0 commit comments

Comments
 (0)