From 95cd868ebdba5dd0b7e1e5276096206a76fa5c77 Mon Sep 17 00:00:00 2001 From: Egor fureunoir Gorbunov Date: Wed, 9 Jul 2025 03:58:05 +0300 Subject: [PATCH] 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; --- core/vendors/__init__.py | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/core/vendors/__init__.py b/core/vendors/__init__.py index f71c2e4e..6c3c4b8e 100644 --- a/core/vendors/__init__.py +++ b/core/vendors/__init__.py @@ -13,6 +13,7 @@ from core.models import ( Brand, Category, Product, + ProductImage, Stock, Vendor, ) @@ -299,18 +300,27 @@ class AbstractVendor: case _: raise ValueError(f"Invalid method {method!r} for products update...") - def delete_inactives(self, inactivation_method: str = "deactivate"): - products = self.get_products_queryset() - + def delete_inactives(self, inactivation_method: str = "deactivate", size: int = 5000): # noinspection PyUnreachableCode match inactivation_method: case "deactivate": - products.filter(is_active=False).delete() + filter_kwargs = {"is_active": False} case "description": - products.filter(description__exact="EVIBES_DELETED_PRODUCT").delete() + filter_kwargs = {"description__exact": "EVIBES_DELETED_PRODUCT"} case _: 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): self.get_products_queryset().delete() self.get_stocks_queryset().delete()