Skip to content

Commit

Permalink
Solve n+1 problem while getting orders list of a user
Browse files Browse the repository at this point in the history
  • Loading branch information
earlinn committed Dec 26, 2023
1 parent 8061693 commit c888fe3
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 16 deletions.
24 changes: 9 additions & 15 deletions backend/api/orders_serializers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import json
import re

from django.db.models import Prefetch
from rest_framework import serializers

from .products_serializers import ProductPresentSerializer
Expand Down Expand Up @@ -92,24 +93,17 @@ class Meta:
)
model = Order

# TODO: commented code doesn't reduce DB hits
@classmethod
def setup_eager_loading(cls, queryset):
"""Perform necessary eager loading of orders data."""
return queryset.select_related("user")
# ).prefetch_related(
# Prefetch(
# "products",
# queryset=Product.objects.select_related(
# "category", "subcategory", "producer"
# ).prefetch_related(
# "components",
# "tags",
# "promotions",
# "reviews",
# ),
# )
# )
return queryset.select_related("user").prefetch_related(
Prefetch(
"orders",
queryset=OrderProduct.objects.select_related(
"product__category"
).prefetch_related("product__promotions"),
)
)


class OrderGetAnonSerializer(serializers.ModelSerializer):
Expand Down
1 change: 0 additions & 1 deletion backend/api/orders_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,6 @@ def retrieve(self, request, **kwargs):
def list(self, request, **kwargs):
if self.request.user.is_authenticated:
queryset = self.get_queryset().filter(user=self.request.user)
# TODO: need to solve n+1 problem
serializer = self.get_serializer(queryset, many=True)
logger.info("The user's order list was successfully received.")
return Response(serializer.data, status=status.HTTP_200_OK)
Expand Down

0 comments on commit c888fe3

Please sign in to comment.