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.
 
 

83 lines
3.4 KiB

import random
from django.core.management.base import BaseCommand
from django.db.models import Q
from apps.hadis.models import Hadis, HadisStatus, HadisTag # REPLACE 'your_app_name'
class Command(BaseCommand):
help = 'Enriches existing Hadis records with Links, Statuses, and Tags based on specific IDs.'
def handle(self, *args, **kwargs):
self.stdout.write(self.style.WARNING('Starting Hadis data enrichment...'))
# 1. FETCH TARGET DATA
# ---------------------------------------------------------
# Status IDs: 126-134
status_ids = list(range(126, 135))
statuses = list(HadisStatus.objects.filter(id__in=status_ids))
# Tag IDs: 507-517 AND 547-571
tag_ids = list(range(507, 518)) + list(range(547, 572))
tags = list(HadisTag.objects.filter(id__in=tag_ids))
# Check if we found the requirements
if not statuses:
self.stdout.write(self.style.ERROR(f"No HadisStatus found for IDs {status_ids}. Please check your DB."))
return
if not tags:
self.stdout.write(self.style.ERROR(f"No HadisTags found for IDs {tag_ids}. Please check your DB."))
return
self.stdout.write(f"Found {len(statuses)} Statuses and {len(tags)} Tags to distribute.")
# 2. ITERATE AND UPDATE HADISES
# ---------------------------------------------------------
hadises = Hadis.objects.all()
count = 0
# Sample data to generate random links
link_sources = [
("Sunnah.com", "https://sunnah.com/bukhari/"),
("IslamWeb", "https://www.islamweb.net/ar/fatwa/"),
("HadithDB", "https://hadithdb.com/"),
("Dorar", "https://dorar.net/hadith/"),
("IslamicFinder", "https://www.islamicfinder.org/"),
("Al-Islam", "https://www.al-islam.org/")
]
for hadis in hadises:
# A. Update Status (One random status from the list)
random_status = random.choice(statuses)
hadis.hadis_status = random_status
# B. Generate Links (At least 3)
# Since links is a JSONField dict, we create a dictionary structure
num_links = random.randint(3, 5) # Generate 3 to 5 links
selected_sources = random.sample(link_sources, num_links)
links_data = {}
for name, base_url in selected_sources:
# Adding a random number to URL to make it look unique
links_data[name] = f"{base_url}{random.randint(1000, 9999)}"
hadis.links = links_data
# Save the direct fields (status and links)
hadis.save()
# C. Update Tags (At least 4-5)
# Note: We must save() the model before adding ManyToMany relations
num_tags = random.randint(4, 5)
# Ensure we don't try to sample more tags than exist
sample_size = min(num_tags, len(tags))
selected_tags = random.sample(tags, sample_size)
# Clear existing tags if you want a fresh start, otherwise remove .clear()
hadis.tags.clear()
hadis.tags.add(*selected_tags)
count += 1
if count % 10 == 0:
self.stdout.write(f"Processed {count} Hadiths...")
self.stdout.write(self.style.SUCCESS(f'Successfully updated {count} Hadis records!'))