From e77a4945775a38a024240a93c5226bb05ae2a5a3 Mon Sep 17 00:00:00 2001 From: calumbell Date: Tue, 19 Nov 2024 11:22:22 +0000 Subject: [PATCH] eager loading on /items endpoint - mitigates N+1 problem --- api_v2/views/item.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/api_v2/views/item.py b/api_v2/views/item.py index 87c2eead..e505ce3b 100644 --- a/api_v2/views/item.py +++ b/api_v2/views/item.py @@ -36,6 +36,24 @@ class ItemViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = serializers.ItemSerializer filterset_class = ItemFilterSet + def get_queryset(self): + depth = int(self.request.query_params.get('depth', 0)) + queryset = ItemViewSet.setup_eager_loading(super().get_queryset(), self.action, depth) + return queryset + + # Eagerly load nested resources to address N+1 problems + @staticmethod + def setup_eager_loading(queryset, action, depth): + if action == 'list': + selects = ['armor', 'weapon'] + # Prefetch many-to-many and reverse ForeignKey relations + prefetches = [ + 'category', 'document', 'document__licenses', + 'damage_immunities', 'damage_resistances', + 'damage_vulnerabilities', 'rarity' + ] + queryset = queryset.select_related(*selects).prefetch_related(*prefetches) + return queryset class ItemRarityViewSet(viewsets.ReadOnlyModelViewSet): """