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): """