From e932d81572275e77f8499fcfd22f17c48a372b13 Mon Sep 17 00:00:00 2001 From: Egor fureunoir Gorbunov Date: Sun, 29 Jun 2025 22:07:59 +0300 Subject: [PATCH] Features: 1) Add management command to delete products with no associated order in batches. Fixes: 1) Remove duplicate field 'is_active' in ProductAdmin.general_fields. Extra: 1) Add transaction management for batch deletions; 2) Improve command output with success message. --- core/admin.py | 2 +- .../commands/delete_never_ordered_products.py | 24 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 core/management/commands/delete_never_ordered_products.py diff --git a/core/admin.py b/core/admin.py index 78f4215a..cec95866 100644 --- a/core/admin.py +++ b/core/admin.py @@ -256,7 +256,7 @@ class ProductAdmin(FieldsetsMixin, BasicModelAdmin): autocomplete_fields = ("category", "brand", "tags") inlines = [AttributeValueInline, ProductImageInline, StockInline] - general_fields = ["is_active", "name", "partnumber", "is_active", "is_digital"] + general_fields = ["is_active", "name", "partnumber", "is_digital"] relation_fields = ["category", "brand", "tags"] diff --git a/core/management/commands/delete_never_ordered_products.py b/core/management/commands/delete_never_ordered_products.py new file mode 100644 index 00000000..84b1ba97 --- /dev/null +++ b/core/management/commands/delete_never_ordered_products.py @@ -0,0 +1,24 @@ +from django.core.management.base import BaseCommand +from django.db import transaction + +from core.models import Product + +CHUNK_SIZE = 5000 + +class Command(BaseCommand): + help = "Delete Product rows with no OrderProduct, in batches" + + def handle(self, *args, **options): + while True: + batch_ids = list( + Product.objects + .filter(orderproduct__isnull=True) + .values_list('pk', flat=True)[:CHUNK_SIZE] + ) + if not batch_ids: + break + with transaction.atomic(): + Product.objects.filter(pk__in=batch_ids).delete() + self.stdout.write(f"Deleted {len(batch_ids)} products…") + + self.stdout.write("✅ All unordered products removed.")