From eea43db5820be54c44fd116c1a25063207b6b34f Mon Sep 17 00:00:00 2001 From: mohsentaba Date: Mon, 9 Feb 2026 13:46:48 +0330 Subject: [PATCH] Refactor HadisCategory serializers to improve Hadith counting logic - Updated `get_children_count` method to calculate the total number of Hadiths in a category and its descendants instead of counting active children categories. - Enhanced code clarity by removing commented-out code and providing detailed docstrings for the new logic. --- apps/hadis/serializers/category.py | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/apps/hadis/serializers/category.py b/apps/hadis/serializers/category.py index 472c792..b7c7a46 100644 --- a/apps/hadis/serializers/category.py +++ b/apps/hadis/serializers/category.py @@ -134,9 +134,18 @@ class HadisCategorySelectSerializer(serializers.ModelSerializer): return Hadis.objects.filter(category=obj, status=True).exists() def get_children_count(self, obj): - """Get count of active children categories that have children or hadis""" - children = obj.get_children().filter(sect=obj.sect) - return len(children) + # """Get count of active children categories that have children or hadis""" + # children = obj.get_children().filter(sect=obj.sect) + # return len(children) + """ + Calculates the total number of Hadiths in this category + and all its descendants (sub-categories). + """ + # 1. Get all descendants of this category (including itself) + family_tree = obj.get_descendants(include_self=True) + + # 2. Count all Hadiths that belong to any category in this tree + return Hadis.objects.filter(category__in=family_tree).count() def get_hadis_count(self,obj): return len(Hadis.objects.filter(category=obj)) @@ -170,9 +179,18 @@ class HadisCategorySelectSourceSerializer(serializers.ModelSerializer): return Hadis.objects.filter(category=obj, status=True).exists() def get_children_count(self, obj): - """Get count of active children categories that have children or hadis""" - children = obj.get_children().filter(sect=obj.sect , source_type= obj.source_type) - return len(children) + # """Get count of active children categories that have children or hadis""" + # children = obj.get_children().filter(sect=obj.sect) + # return len(children) + """ + Calculates the total number of Hadiths in this category + and all its descendants (sub-categories). + """ + # 1. Get all descendants of this category (including itself) + family_tree = obj.get_descendants(include_self=True) + + # 2. Count all Hadiths that belong to any category in this tree + return Hadis.objects.filter(category__in=family_tree).count() def get_hadis_count(self,obj): return len(Hadis.objects.filter(category=obj))