# backend/apps/hadis/management/commands/seed_edition_researchers.py import random from django.core.management.base import BaseCommand from django.db import transaction from django.utils.text import slugify from apps.hadis.models import BookEdition, BookAuthor, BookResearcher class Command(BaseCommand): help = 'Assigns two researchers to each BookEdition: one random text-only, one linked to a random existing BookAuthor.' def handle(self, *args, **options): self.stdout.write(self.style.WARNING("Starting to seed edition researchers...")) editions = list(BookEdition.objects.all()) authors = list(BookAuthor.objects.all()) if not editions: self.stdout.write(self.style.ERROR("No BookEditions found in the database.")) return if not authors: self.stdout.write(self.style.ERROR("No BookAuthors found. Please add some authors first.")) return # 1. Clean existing researchers self.stdout.write("Deleting existing BookResearchers...") BookResearcher.objects.all().delete() random_researcher_names = [ {"fa": "دکتر سید علی موسوی", "en": "Dr. Seyed Ali Mousavi"}, {"fa": "استاد محمد کریمی", "en": "Professor Mohammad Karimi"}, {"fa": "دکتر رضا علوی", "en": "Dr. Reza Alavi"}, {"fa": "پژوهشگر حمید احمدی", "en": "Researcher Hamid Ahmadi"}, {"fa": "دکتر مریم رضایی", "en": "Dr. Maryam Rezaei"}, {"fa": "استاد فاطمه حسینی", "en": "Professor Fatemeh Hosseini"}, {"fa": "دکتر جعفر صادقی", "en": "Dr. Jafar Sadeghi"}, ] text_only_count = 0 linked_author_count = 0 with transaction.atomic(): for edition in editions: # 1. First researcher: Text-only (Random Name & Slug) name_data = random.choice(random_researcher_names) name_field = [ {"language_code": "fa", "text": name_data["fa"]}, {"language_code": "en", "text": name_data["en"]}, ] # Ensure clean slug base_slug = slugify(name_data["en"]) slug_val = base_slug counter = 1 while BookResearcher.objects.filter(slug=slug_val).exists(): slug_val = f"{base_slug}-{counter}" counter += 1 BookResearcher.objects.create( book_edition=edition, name=name_field, slug=slug_val, author=None ) text_only_count += 1 # 2. Second researcher: Linked to a random BookAuthor random_author = random.choice(authors) BookResearcher.objects.create( book_edition=edition, author=random_author ) linked_author_count += 1 self.stdout.write( self.style.SUCCESS( f"Successfully seeded researchers for {len(editions)} BookEditions!\n" f"- Created {text_only_count} text-only researchers.\n" f"- Created {linked_author_count} researchers linked to existing authors." ) )