# backend/apps/hadis/management/commands/seed_book_excerpts.py import random from django.core.management.base import BaseCommand from django.db import transaction from apps.hadis.models import BookReference, Hadis, HadisReference class Command(BaseCommand): help = 'Assigns 4-5 random Hadis excerpts to all BookReferences.' def handle(self, *args, **options): self.stdout.write(self.style.WARNING("Scanning books and hadiths...")) books = BookReference.objects.all() # گرفتن تمام آیدی‌های احادیث به صورت یک لیست تخت برای انتخاب رندوم سریع all_hadis_ids = list(Hadis.objects.filter(status=True).values_list('id', flat=True)) if not books.exists(): self.stdout.write(self.style.ERROR("❌ No BookReferences found in the database.")) return if not all_hadis_ids: self.stdout.write(self.style.ERROR("❌ No active Hadis found to assign as excerpts.")) return new_references = [] total_books = books.count() self.stdout.write(self.style.WARNING(f"Processing {total_books} books...")) for book in books: # انتخاب تصادفی ۴ یا ۵ اکسرپت num_excerpts = random.randint(4, 5) # در صورتی که تعداد کل احادیث کمتر از ۵ تا باشد num_excerpts = min(num_excerpts, len(all_hadis_ids)) # انتخاب رندوم آیدی احادیث selected_hadis_ids = random.sample(all_hadis_ids, num_excerpts) # استخراج احادیثی که از قبل به این کتاب وصل بوده‌اند (برای جلوگیری از ثبت تکراری) existing_hadis_ids = set(HadisReference.objects.filter( book_reference=book, hadis_id__in=selected_hadis_ids ).values_list('hadis_id', flat=True)) for h_id in selected_hadis_ids: if h_id not in existing_hadis_ids: new_references.append( HadisReference( book_reference=book, hadis_id=h_id, # تولید دیتای دامی برای فیلدهای متنی رفرنس volume=f"Vol. {random.randint(1, 10)}", pages=str(random.randint(15, 450)), hadith_number=str(random.randint(100, 9999)) ) ) if new_references: with transaction.atomic(): HadisReference.objects.bulk_create(new_references, batch_size=1000) self.stdout.write(self.style.SUCCESS(f"🎉 Successfully created {len(new_references)} new excerpts for books!")) else: self.stdout.write(self.style.SUCCESS("✅ All books already have these excerpts or no new ones needed."))