Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API V2: Fixed N+1 problem on /items endpoint #609

Merged
merged 1 commit into from
Nov 23, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading