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.
 
 

76 lines
2.2 KiB

from django.core.management.base import BaseCommand
from django.db import transaction
from apps.hadis.models import Hadis
def normalize_translation(value):
"""
Convert:
{"en": "translation", "fa": "ترجمه"}
to:
[{"text": "translation", "language_code": "en"},
{"text": "ترجمه", "language_code": "fa"}]
Also clean existing list entries by:
- ensuring only 'text' + 'language_code'
- dropping any 'title' key
"""
if value is None:
return []
# If it's already a list, clean its items
if isinstance(value, list):
cleaned = []
for item in value:
if not isinstance(item, dict):
continue
lang = item.get("language_code")
# prefer 'text', fallback to 'title'
text = item.get("text") or item.get("title")
if not lang or not text:
continue
cleaned.append(
{
"language_code": str(lang),
"text": text,
}
)
return cleaned
# Old dict format: {"en": "...", "fa": "..."}
if isinstance(value, dict):
result = []
for lang_code, text in value.items():
if text is None or text == "":
continue
result.append(
{
"language_code": str(lang_code),
"text": text,
}
)
return result
return []
class Command(BaseCommand):
help = "Reformat Hadis.translation from {'en': '...', 'fa': '...'} to [{'text': '...', 'language_code': '...'}, ...]" # noqa: E501
@transaction.atomic
def handle(self, *args, **options):
qs = Hadis.objects.all()
total = qs.count()
self.stdout.write(f"Found {total} hadis objects")
changed = 0
for hadis in qs:
old = hadis.translation
new = normalize_translation(old)
if new != old:
hadis.translation = new
hadis.save(update_fields=["translation"])
changed += 1
self.stdout.write(self.style.SUCCESS(f"Updated {changed} hadis objects"))