Skip to content

Commit 2b0582d

Browse files
Merge pull request open5e#609 from calumbell/bugfix/v2-item-n+1
API V2: Fixed N+1 problem on `/items` endpoint
2 parents 2df92ba + e77a494 commit 2b0582d

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

api_v2/views/item.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,24 @@ class ItemViewSet(viewsets.ReadOnlyModelViewSet):
3636
serializer_class = serializers.ItemSerializer
3737
filterset_class = ItemFilterSet
3838

39+
def get_queryset(self):
40+
depth = int(self.request.query_params.get('depth', 0))
41+
queryset = ItemViewSet.setup_eager_loading(super().get_queryset(), self.action, depth)
42+
return queryset
43+
44+
# Eagerly load nested resources to address N+1 problems
45+
@staticmethod
46+
def setup_eager_loading(queryset, action, depth):
47+
if action == 'list':
48+
selects = ['armor', 'weapon']
49+
# Prefetch many-to-many and reverse ForeignKey relations
50+
prefetches = [
51+
'category', 'document', 'document__licenses',
52+
'damage_immunities', 'damage_resistances',
53+
'damage_vulnerabilities', 'rarity'
54+
]
55+
queryset = queryset.select_related(*selects).prefetch_related(*prefetches)
56+
return queryset
3957

4058
class ItemRarityViewSet(viewsets.ReadOnlyModelViewSet):
4159
"""

0 commit comments

Comments
 (0)