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.
 
 
 
 
 

91 lines
3.1 KiB

import random
from django.core.management.base import BaseCommand
from apps.hadis.models.transmitter import Transmitters, TransmitterRelative, RELATION_TYPE_MAP
class Command(BaseCommand):
help = "Assign 1 random father and 2 random sons to every transmitter."
def add_arguments(self, parser):
parser.add_argument(
"--clear",
action="store_true",
help="Clear existing father/relative children relationships before assigning.",
)
def handle(self, *args, **options):
transmitters = list(Transmitters.objects.all())
total_count = len(transmitters)
if total_count < 4:
self.stdout.write(
self.style.ERROR(
f"Not enough transmitters found (found {total_count}, need at least 4)."
)
)
return
self.stdout.write(
self.style.NOTICE(
f"Starting random family assignment for {total_count} transmitters..."
)
)
relatives_to_create = []
updated_count = 0
for tr in transmitters:
# Available candidates excluding self
candidates = [t for t in transmitters if t.id != tr.id]
# 1. Pick 1 random father
father = random.choice(candidates)
tr.father = father
tr.save(update_fields=["father"])
# Remove father from candidates for sons
son_candidates = [t for t in candidates if t.id != father.id]
if len(son_candidates) < 2:
son_candidates = candidates
# 2. Pick 2 random sons
sons = random.sample(son_candidates, 2)
# Clear old children relatives for this transmitter
TransmitterRelative.objects.filter(
related_to=tr, relation_type="children"
).delete()
# Prepare 2 children relatives
for son in sons:
son_name = ""
if son.full_name and isinstance(son.full_name, list) and len(son.full_name) > 0:
first = son.full_name[0]
if isinstance(first, dict):
son_name = first.get("text", "")
if not son_name and hasattr(son, "get_name"):
son_name = son.get_name("en") or son.get_name("ar") or f"Narrator {son.id}"
relatives_to_create.append(
TransmitterRelative(
related_to=tr,
relation_type="children",
relation_value=RELATION_TYPE_MAP.get("children", []),
name=son_name,
narrator=son,
)
)
updated_count += 1
if updated_count % 10 == 0:
self.stdout.write(f"Processed {updated_count}/{total_count}...")
if relatives_to_create:
TransmitterRelative.objects.bulk_create(relatives_to_create)
self.stdout.write(
self.style.SUCCESS(
f"Successfully assigned 1 father and 2 sons to all {updated_count} transmitters!"
)
)