# backend/apps/hadis/management/commands/sync_interpretation_slugs.py from django.core.management.base import BaseCommand from django.db import transaction from apps.hadis.models import HadisInterpretation class Command(BaseCommand): help = 'Syncs existing HadisInterpretation slugs with their Category slugs.' def handle(self, *args, **options): self.stdout.write(self.style.WARNING("Starting to sync interpretation slugs...")) # استفاده از select_related برای جلوگیری از N+1 Query روی Category interpretations = list(HadisInterpretation.objects.select_related('category').all()) if not interpretations: self.stdout.write(self.style.ERROR("No HadisInterpretations found in the database.")) return to_update = [] for obj in interpretations: if obj.category and obj.category.slug: # فقط اگر اسلاگ فرق داشت آپدیت کن تا دیتابیس بی‌دلیل درگیر نشود if obj.slug != obj.category.slug: obj.slug = obj.category.slug to_update.append(obj) if to_update: with transaction.atomic(): batch_size = 1000 for i in range(0, len(to_update), batch_size): HadisInterpretation.objects.bulk_update( to_update[i:i + batch_size], ['slug'] ) self.stdout.write( self.style.SUCCESS(f"\n🎉 Successfully synced slugs for {len(to_update)} interpretations!") ) else: self.stdout.write( self.style.SUCCESS("\n✅ All interpretations already have the correct slug. Nothing to update.") )