schon/core/management/commands/rebuild_slugs.py
Egor fureunoir Gorbunov 30144c5b6a Features: 1) Add image field to search result types (SearchProductsResultsType, SearchCategoriesResultsType, SearchBrandsResultsType); 2) Enhance tags field for categories with DjangoFilterConnectionField; 3) Implement descriptive error handling in rebuild_slugs script.
Fixes: 1) Correct inconsistent function calls with improved attribute formatting; 2) Fix invalid key usage (`uuid` vs. `pk`) in slug rebuilding logic to prevent uniqueness errors; 3) Ensure correct `query` usage in `process_query` function calls.

Extra: Reformat code for readability by updating indentation, and breaking long function signatures and expressions into multiple lines.
2025-06-18 23:03:50 +03:00

53 lines
1.9 KiB
Python

from django.core.management.base import BaseCommand
from django.db import transaction
from django.utils.crypto import get_random_string
from core.models import Brand, Category, Product
class Command(BaseCommand):
help = "Rebuild slug field for all slugified instances"
def reset_em(self, queryset):
total = queryset.count()
self.stdout.write(
f"Starting slug rebuilding for {total} {queryset.model._meta.verbose_name_plural}"
)
for idx, instance in enumerate(queryset.iterator(), start=1):
try:
while (
queryset.filter(name=instance.name)
.exclude(uuid=instance.uuid)
.count()
>= 1
):
instance.name = f"{instance.name} - {get_random_string(length=3, allowed_chars='0123456789')}"
instance.save()
instance.slug = None
with transaction.atomic():
instance.save(update_fields=["slug"])
self.stdout.write(
self.style.SUCCESS(
f"[{idx}/{total}] ({queryset.model._meta.verbose_name_plural} UUID:"
f" {instance.pk}) slug set to '{instance.slug}'"
)
)
except Exception as e:
self.stderr.write(
self.style.ERROR(
f"[{idx}/{total}] ({queryset.model._meta.verbose_name_plural}: {instance.name}/{instance.uuid})"
f" ERROR: {e}"
)
)
def handle(self, *args, **options):
for queryset in [
Brand.objects.all(),
Category.objects.all(),
Product.objects.all(),
]:
self.reset_em(queryset)
self.stdout.write(self.style.SUCCESS("Slug rebuild complete."))