Skip to content

Commit 5e3022d

Browse files
fix(shop): prevent division by zero in product rating calculation
The get_rating method in ProductSerializer did not handle cases where a product had no reviews, resulting in a ZeroDivisionError. This fix adds a check to ensure the number of reviews is greater than zero before performing the division. If there are no reviews, the average rating defaults to 0.0.
1 parent a8710a9 commit 5e3022d

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

shop/serializers.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,10 @@ def get_rating(self, obj):
6969
cache.set(cache_key, cached_data, 604800) # Cache for 1 week (604800 seconds)
7070
else:
7171
# Update cache incrementally
72-
cached_data["average"] = cached_data["total_rating"] / cached_data["count"]
72+
if cached_data["count"] > 0:
73+
cached_data["average"] = cached_data["total_rating"] / cached_data["count"]
74+
else:
75+
cached_data["average"] = 0.0
7376

7477
return {"average": cached_data["average"], "count": cached_data["count"]}
7578

0 commit comments

Comments
 (0)