update
This commit is contained in:
@@ -3,8 +3,8 @@ from rest_framework.decorators import action
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.pagination import PageNumberPagination
|
||||
from django_filters.rest_framework import DjangoFilterBackend
|
||||
from django.db.models import Q
|
||||
from .models import CaseStudy, CaseStudyCategory, Client
|
||||
from django.db.models import Q, Prefetch
|
||||
from .models import CaseStudy, CaseStudyCategory, Client, CaseStudyImage, CaseStudyProcess
|
||||
from .serializers import (
|
||||
CaseStudyListSerializer,
|
||||
CaseStudyDetailSerializer,
|
||||
@@ -42,6 +42,12 @@ class CaseStudyViewSet(viewsets.ReadOnlyModelViewSet):
|
||||
def get_queryset(self):
|
||||
queryset = super().get_queryset()
|
||||
|
||||
# Always optimize foreign key lookups
|
||||
queryset = queryset.select_related('category', 'client')
|
||||
|
||||
# Don't add prefetch_related here for retrieve action - it's handled in retrieve() method
|
||||
# to avoid duplicate prefetch lookups
|
||||
|
||||
# Filter by category
|
||||
category_slug = self.request.query_params.get('category', None)
|
||||
if category_slug and category_slug != 'all':
|
||||
@@ -64,9 +70,31 @@ class CaseStudyViewSet(viewsets.ReadOnlyModelViewSet):
|
||||
return queryset.distinct()
|
||||
|
||||
def retrieve(self, request, *args, **kwargs):
|
||||
"""Override retrieve to increment view count"""
|
||||
instance = self.get_object()
|
||||
"""Override retrieve to increment view count and ensure optimized queryset"""
|
||||
# Get the base queryset (without prefetch_related to avoid duplicates)
|
||||
queryset = self.filter_queryset(self.get_queryset())
|
||||
|
||||
# Now add prefetch_related for detail view optimization
|
||||
queryset = queryset.prefetch_related(
|
||||
Prefetch(
|
||||
'gallery_images',
|
||||
queryset=CaseStudyImage.objects.order_by('display_order', 'created_at')
|
||||
),
|
||||
Prefetch(
|
||||
'process_steps',
|
||||
queryset=CaseStudyProcess.objects.order_by('step_number')
|
||||
)
|
||||
)
|
||||
|
||||
# Get the object using the optimized queryset
|
||||
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
|
||||
filter_kwargs = {self.lookup_field: kwargs[lookup_url_kwarg]}
|
||||
instance = queryset.get(**filter_kwargs)
|
||||
|
||||
# Increment view count
|
||||
instance.increment_views()
|
||||
|
||||
# Serialize and return
|
||||
serializer = self.get_serializer(instance)
|
||||
return Response(serializer.data)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user