From b849d4fcdaa526d978ad298c66625280b8717d07 Mon Sep 17 00:00:00 2001 From: Tyler Reed Date: Mon, 21 Oct 2024 11:36:56 -0600 Subject: [PATCH] Fixing up spell endpoint to fetch all needed data beforehand --- api_v2/views/spell.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/api_v2/views/spell.py b/api_v2/views/spell.py index 8aa46ea8..cbe69424 100644 --- a/api_v2/views/spell.py +++ b/api_v2/views/spell.py @@ -38,3 +38,23 @@ class SpellViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = serializers.SpellSerializer filterset_class = SpellFilterSet + def get_queryset(self): + queryset = models.Spell.objects.all().order_by('pk') + depth = self.get_serializer().Meta.depth + queryset = SpellViewSet.setup_eager_loading(queryset, depth) + return queryset + + @staticmethod + def setup_eager_loading(queryset, depth): + selects = ['document', 'school'] + prefetches = ['classes', 'spellcastingoption_set'] + + if depth >= 1: + prefetches = prefetches + ['document__licenses'] + + if depth >= 2: + prefetches = prefetches + ['document__gamesystem', 'document__publisher'] + + queryset = queryset.select_related(*selects).prefetch_related(*prefetches) + return queryset +