You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

50 lines
2.2 KiB

# backend/apps/hadis/management/commands/generate_author_slugs.py
from django.core.management.base import BaseCommand
from apps.hadis.models.reference import BookAuthor
class Command(BaseCommand):
help = 'Generates missing slugs for BookAuthor records.'
def add_arguments(self, parser):
# اضافه کردن یک قابلیت اختیاری برای ساخت مجدد تمام اسلاگ‌ها
parser.add_argument(
'--all',
action='store_true',
help='Regenerate slugs for ALL authors, even if they already have one.',
)
def handle(self, *args, **options):
regenerate_all = options['all']
if regenerate_all:
# گرفتن همه نویسنده‌ها
authors = BookAuthor.objects.all()
self.stdout.write(self.style.WARNING(f"Regenerating slugs for ALL {authors.count()} authors..."))
else:
# گرفتن نویسنده‌هایی که اسلاگ ندارند یا اسلاگشان خالی است
authors = BookAuthor.objects.filter(slug__isnull=True) | BookAuthor.objects.filter(slug='')
self.stdout.write(self.style.WARNING(f"Generating slugs for {authors.count()} authors without a slug..."))
if not authors.exists():
self.stdout.write(self.style.SUCCESS("All authors already have slugs. Nothing to do!"))
return
updated_count = 0
for author in authors:
if regenerate_all:
author.slug = '' # خالی کردن اسلاگ تا متد save مجبور به ساخت مجدد شود
# صدا زدن متد save باعث می‌شود منطق اسلاگ‌سازِ داخل مدل شما به صورت خودکار اجرا شود
author.save()
updated_count += 1
# چاپ لاگ پیشرفت برای هر 100 رکورد
if updated_count % 100 == 0:
self.stdout.write(f"Processed {updated_count} authors...")
self.stdout.write(
self.style.SUCCESS(
f"\n🎉 Successfully generated/updated slugs for {updated_count} BookAuthors!"
)
)