update product.view of product

This commit is contained in:
Parsa Nazer
2026-05-12 09:02:39 +03:30
parent 6f93808ec3
commit 9b19258fd2
+6
View File
@@ -141,6 +141,8 @@ class ProductView(APIView):
},
)
def get(self, request, slug):
from django.db.models import F
# Optimize query with select_related and prefetch_related to avoid N+1 queries
product = get_object_or_404(
ProductModel.objects.select_related(
@@ -158,6 +160,10 @@ class ProductView(APIView):
slug=slug
)
# Increment product view count atomically using F expressions to avoid race conditions
ProductModel.objects.filter(id=product.id).update(view=F('view') + 1)
product.view += 1 # Update in-memory instance for response
if request.user.is_authenticated:
cart_obj, _ = Cart.objects.get_or_create(user=request.user)
# Optimize cart items query - prefetch all related data