Skip to content

Solve n+1 problem while getting orders list of a user #219

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

Merged
merged 1 commit into from
Dec 26, 2023
Merged
Show file tree
Hide file tree
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
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