Fixes: 1) Update slug population logic in management commands. Extra: Refactor renderer class formatting, query processing, and formatting for readability across multiple files.
50 lines
1.8 KiB
Python
50 lines
1.8 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:
|
|
if (
|
|
queryset.filter(name=instance.name).exclude(pk=instance.pk).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.pk}) 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."))
|