From 3caab8f523c7304b8c27e7af8094a0e4894b18e7 Mon Sep 17 00:00:00 2001 From: Egor fureunoir Gorbunov Date: Wed, 30 Apr 2025 16:58:57 +0300 Subject: [PATCH] Add management command to populate Product slugs Introduce a Django management command to populate the `slug` field for Product instances where it is null. The command processes products in batches, handles errors gracefully, and logs issues for troubleshooting. --- core/management/commands/populate_slugs.py | 31 ++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 core/management/commands/populate_slugs.py diff --git a/core/management/commands/populate_slugs.py b/core/management/commands/populate_slugs.py new file mode 100644 index 00000000..69299ccb --- /dev/null +++ b/core/management/commands/populate_slugs.py @@ -0,0 +1,31 @@ +import logging + +from django.core.management.base import BaseCommand +from django.db import transaction +from core.models import Product + +logger = logging.getLogger(__name__) + + +class Command(BaseCommand): + help = "Populate slug field for all Product instances" + + def handle(self, *args, **options): + qs = Product.objects.filter(slug__isnull=True) + total = qs.count() + self.stdout.write(f"Starting slug population for {total} products") + + for idx, product in enumerate(qs.iterator(), start=1): + try: + product.slug = None + with transaction.atomic(): + product.save(update_fields=["slug"]) + + self.stdout.write( + self.style.SUCCESS(f"[{idx}/{total}] (Product ID: {product.pk}) slug set to '{product.slug}'") + ) + except Exception as e: + logger.exception(f"Product {product.pk}: slug population failed") + self.stderr.write(self.style.ERROR(f"[{idx}/{total}] (Product ID: {product.pk}) ERROR: {e}")) + + self.stdout.write(self.style.SUCCESS("Slug population complete."))