Features: 1) Add support for batched deletion of inactive products in delete_inactives with configurable batch size; 2) Include ProductImage in imports for cleanup operations;

Fixes: 1) Ensure `delete_inactives` handles deletions safely by using query batching; 2) Correct filter logic in `delete_inactives` for inactivation methods;

Extra: Refactor `delete_inactives` logic for better maintainability and clearer error handling;
This commit is contained in:
Egor Pavlovich Gorbunov 2025-07-09 03:58:05 +03:00
parent 4160e29455
commit 95cd868ebd

View file

@ -13,6 +13,7 @@ from core.models import (
Brand, Brand,
Category, Category,
Product, Product,
ProductImage,
Stock, Stock,
Vendor, Vendor,
) )
@ -299,18 +300,27 @@ class AbstractVendor:
case _: case _:
raise ValueError(f"Invalid method {method!r} for products update...") raise ValueError(f"Invalid method {method!r} for products update...")
def delete_inactives(self, inactivation_method: str = "deactivate"): def delete_inactives(self, inactivation_method: str = "deactivate", size: int = 5000):
products = self.get_products_queryset()
# noinspection PyUnreachableCode # noinspection PyUnreachableCode
match inactivation_method: match inactivation_method:
case "deactivate": case "deactivate":
products.filter(is_active=False).delete() filter_kwargs = {"is_active": False}
case "description": case "description":
products.filter(description__exact="EVIBES_DELETED_PRODUCT").delete() filter_kwargs = {"description__exact": "EVIBES_DELETED_PRODUCT"}
case _: case _:
raise ValueError(f"Invalid method {inactivation_method!r} for products cleaner...") raise ValueError(f"Invalid method {inactivation_method!r} for products cleaner...")
while True:
batch_ids = list(self.get_products_queryset()
.filter(**filter_kwargs)
.values_list("pk", flat=True)[:size])
if not batch_ids:
break
with suppress(Exception):
AttributeValue.objects.filter(product_id__in=batch_ids).delete()
ProductImage.objects.filter(product_id__in=batch_ids).delete()
Product.objects.filter(pk__in=batch_ids).delete()
def delete_belongings(self): def delete_belongings(self):
self.get_products_queryset().delete() self.get_products_queryset().delete()
self.get_stocks_queryset().delete() self.get_stocks_queryset().delete()