Skip to content

Commit

Permalink
added selecting and prefetching of related fields to CreatureViewSet
Browse files Browse the repository at this point in the history
  • Loading branch information
calumbell committed Nov 10, 2024
1 parent 8733d54 commit dee7c0b
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions api_v2/views/creature.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,30 @@ class CreatureViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = serializers.CreatureSerializer
filterset_class = CreatureFilterSet

def get_queryset(self):
# Retrieve depth from query params, default to 0 if not provided
depth = int(self.request.query_params.get('depth', 0))
queryset = CreatureViewSet.setup_eager_loading(super().get_queryset(), self.action, depth)
return queryset

@staticmethod
def setup_eager_loading(queryset, action, depth):
# Apply select_related and prefetch_related based on action and depth
if action == 'list':
selects = ['type', 'size', 'document']

# Many-to-many and reverse relationships for prefetching
prefetches = [
'creatureaction_set', 'condition_immunities', 'damage_immunities',
'damage_vulnerabilities', 'damage_resistances', 'environments',
'document'
]

if depth >= 2:
prefetches += ['document__publisher', 'document__licenses', 'document__gamesystem']
queryset = queryset.select_related(*selects).prefetch_related(*prefetches)
return queryset


class CreatureTypeFilterSet(FilterSet):
class Meta:
Expand Down

0 comments on commit dee7c0b

Please sign in to comment.