Features: 1) Add annotations to filter products based on both own and descendant categories; 2) Enhance filter_whole_categories logic to use annotated product existence checks;

Fixes: 1) Correct filtering logic for categories without products;

Extra: Refactor `filter_whole_categories` for improved readability and maintainability;
This commit is contained in:
Egor Pavlovich Gorbunov 2025-06-17 11:50:41 +03:00
parent 0153157653
commit 61561b4a80

View file

@ -335,9 +335,27 @@ class CategoryFilter(FilterSet):
fields = ["uuid", "name", "parent_uuid", "slug", "tags", "level", "order_by", "whole"]
def filter_whole_categories(self, queryset, _name, value):
descendant_cats = Category.objects.filter(
tree_id=OuterRef('tree_id'),
lft__gt=OuterRef('lft'),
rght__lt=OuterRef('rght'),
).values('pk')
has_own_products = Exists(
Product.objects.filter(category=OuterRef('pk'))
)
has_desc_products = Exists(
Product.objects.filter(category_id__in=descendant_cats)
)
annotated = queryset.annotate(
has_products=has_own_products | has_desc_products
)
if value:
return queryset.filter(products__isnull=False).distinct()
return queryset.filter(products__isnull=True).distinct()
return annotated.filter(has_products=True).distinct()
else:
return annotated.filter(has_products=False).distinct()
def filter_parent_uuid(self, queryset, _name, value):
if value in ("", "null", "None"):