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:
parent
0153157653
commit
61561b4a80
1 changed files with 20 additions and 2 deletions
|
|
@ -335,9 +335,27 @@ class CategoryFilter(FilterSet):
|
||||||
fields = ["uuid", "name", "parent_uuid", "slug", "tags", "level", "order_by", "whole"]
|
fields = ["uuid", "name", "parent_uuid", "slug", "tags", "level", "order_by", "whole"]
|
||||||
|
|
||||||
def filter_whole_categories(self, queryset, _name, value):
|
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:
|
if value:
|
||||||
return queryset.filter(products__isnull=False).distinct()
|
return annotated.filter(has_products=True).distinct()
|
||||||
return queryset.filter(products__isnull=True).distinct()
|
else:
|
||||||
|
return annotated.filter(has_products=False).distinct()
|
||||||
|
|
||||||
def filter_parent_uuid(self, queryset, _name, value):
|
def filter_parent_uuid(self, queryset, _name, value):
|
||||||
if value in ("", "null", "None"):
|
if value in ("", "null", "None"):
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue