Optimize product count retrieval and enhance query performance with prefetch_related

This commit is contained in:
Parsa Nazer
2025-11-03 11:56:47 +03:30
parent d760a50da5
commit bf0817ed34
2 changed files with 15 additions and 3 deletions
+3 -1
View File
@@ -102,7 +102,9 @@ class SubCategorySerializer(serializers.ModelSerializer):
'meta_description', 'product_count', 'parent', 'image']
def get_product_count(self, obj):
return obj.products.count()
# Use annotated product_count if available (from optimized query)
# Otherwise fall back to counting (for backward compatibility)
return getattr(obj, 'product_count', obj.products.count())
def get_parent(self, obj):
return obj.parent.name