Skip to content

Commit

Permalink
eager loading on /items endpoint - mitigates N+1 problem
Browse files Browse the repository at this point in the history
  • Loading branch information
calumbell committed Nov 19, 2024
1 parent a877c84 commit e77a494
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions api_v2/views/item.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand Down

0 comments on commit e77a494

Please sign in to comment.