rateing system
This commit is contained in:
@@ -134,6 +134,12 @@ class ProductView(APIView):
|
||||
permission_classes = [AllowAny]
|
||||
# authentication_classes = []
|
||||
|
||||
@extend_schema(
|
||||
responses={
|
||||
200: DynamicProductSerializer(context={'view_type': 'instance'}),
|
||||
404: OpenApiTypes.OBJECT,
|
||||
},
|
||||
)
|
||||
def get(self, request, slug):
|
||||
# Optimize query with select_related and prefetch_related to avoid N+1 queries
|
||||
product = get_object_or_404(
|
||||
@@ -147,6 +153,7 @@ class ProductView(APIView):
|
||||
'variants__details__detail_category',
|
||||
'related_products__variants__product_attributes',
|
||||
'related_products__category',
|
||||
'ratings',
|
||||
),
|
||||
slug=slug
|
||||
)
|
||||
@@ -662,3 +669,51 @@ class BotCategoryView(APIView):
|
||||
"success": False,
|
||||
"categories": []
|
||||
})
|
||||
|
||||
|
||||
class ProductRatingView(APIView):
|
||||
"""
|
||||
API endpoint to submit/update a product rating
|
||||
POST: /api/products/<slug>/rating/
|
||||
"""
|
||||
permission_classes = [IsAuthenticatedOrReadOnly]
|
||||
serializer_class = ProductRatingSerializer
|
||||
def post(self, request, slug):
|
||||
if not request.user.is_authenticated:
|
||||
return Response(
|
||||
{'detail': 'احراز هویت الزامی است'},
|
||||
status=status.HTTP_401_UNAUTHORIZED
|
||||
)
|
||||
|
||||
product = get_object_or_404(ProductModel, slug=slug)
|
||||
|
||||
# Check if user already rated this product
|
||||
existing_rating = ProductRating.objects.filter(
|
||||
product=product,
|
||||
user=request.user
|
||||
).exists()
|
||||
|
||||
if existing_rating:
|
||||
return Response(
|
||||
{'detail': 'شما قبلا این محصول را امتیاز دادید'},
|
||||
status=status.HTTP_400_BAD_REQUEST
|
||||
)
|
||||
|
||||
serializer = ProductRatingSerializer(
|
||||
data=request.data,
|
||||
context={'product_id': product.id, 'request': request}
|
||||
)
|
||||
|
||||
if serializer.is_valid():
|
||||
serializer.save()
|
||||
|
||||
# Invalidate cache for this product
|
||||
from django.core.cache import cache
|
||||
cache.delete(f'product_avg_rating_{product.id}')
|
||||
|
||||
return Response(
|
||||
{'detail': 'امتیاز شما با موفقیت ثبت شد'},
|
||||
status=status.HTTP_201_CREATED
|
||||
)
|
||||
|
||||
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
Reference in New Issue
Block a user