# backend/apps/hadis/management/commands/seed_opinion_scholars.py import random from django.core.management.base import BaseCommand from django.db import transaction from apps.hadis.models import TransmitterOpinion, BookAuthor class Command(BaseCommand): help = 'Randomly assigns BookAuthors to existing TransmitterOpinions as scholars.' def handle(self, *args, **options): self.stdout.write(self.style.WARNING("Starting to link opinions to random scholars...")) # دریافت تمام رکوردها opinions = list(TransmitterOpinion.objects.all()) authors = list(BookAuthor.objects.all()) if not opinions: self.stdout.write(self.style.ERROR("No TransmitterOpinions found in the database.")) return if not authors: self.stdout.write(self.style.ERROR("No BookAuthors found. Please add some authors first.")) return opinions_to_update = [] # تخصیص رندوم نویسنده‌ها به نظرات for opinion in opinions: random_scholar = random.choice(authors) opinion.scholar = random_scholar opinions_to_update.append(opinion) # آپدیت گروهی (Bulk Update) برای پرفورمنس بالا with transaction.atomic(): batch_size = 1000 for i in range(0, len(opinions_to_update), batch_size): TransmitterOpinion.objects.bulk_update( opinions_to_update[i:i + batch_size], ['scholar'] # فقط فیلد scholar آپدیت می‌شود ) self.stdout.write( self.style.SUCCESS( f"\n🎉 Successfully linked {len(opinions_to_update)} TransmitterOpinions to random BookAuthors (Scholars)!" ) )