Features: 1) Add chunk size argument for deleting never ordered products;

Fixes: 1) Improve error handling with detailed exception logging during deletion;

Extra: 1) Replace hardcoded chunk size with a dynamic option; 2) Enhance log output for better debugging.
This commit is contained in:
Egor Pavlovich Gorbunov 2025-07-05 02:47:35 +03:00
parent db0d64bfd2
commit d3dd23d99f

View file

@ -2,16 +2,24 @@ from django.core.management.base import BaseCommand
from core.models import AttributeValue, Product, ProductImage
CHUNK_SIZE = 5000
class Command(BaseCommand):
help = "Delete Product rows with no OrderProduct, in batches"
def add_arguments(self, parser):
parser.add_argument(
"-s",
"--size",
required=False,
default=5000,
help="Chunk size to delete",
)
def handle(self, *args, **options):
size = options["size"]
while True:
batch_ids = list(
Product.objects.filter(orderproduct__isnull=True).values_list("pk", flat=True)[:CHUNK_SIZE]
Product.objects.filter(orderproduct__isnull=True).values_list("pk", flat=True)[:size]
)
if not batch_ids:
break
@ -19,7 +27,8 @@ class Command(BaseCommand):
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()
except Exception:
except Exception as e:
self.stdout.write("Couldn't delete some of the products(will retry later): %s" % str(e))
continue
self.stdout.write(f"Deleted {len(batch_ids)} products…")