Skip to content

Commit

Permalink
Merge pull request #609 from calumbell/bugfix/v2-item-n+1
Browse files Browse the repository at this point in the history
API V2: Fixed N+1 problem on `/items` endpoint
  • Loading branch information
augustjohnson authored Nov 23, 2024
2 parents 2df92ba + e77a494 commit 2b0582d
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 2b0582d

Please sign in to comment.