Browse Source

fixed and reformat hadis translation data with command script

master
Mohsen Taba 5 months ago
parent
commit
60a38d449d
  1. 76
      apps/hadis/management/commands/reformat_translations.py
  2. 13
      apps/hadis/serializers/hadis.py
  3. 2
      apps/hadis/views/hadis.py

76
apps/hadis/management/commands/reformat_translations.py

@ -0,0 +1,76 @@
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"))

13
apps/hadis/serializers/hadis.py

@ -153,10 +153,9 @@ class HadisSyncSerializer(serializers.ModelSerializer):
class HadisListSerializer(serializers.ModelSerializer): class HadisListSerializer(serializers.ModelSerializer):
"""Serializer for Hadis list""" """Serializer for Hadis list"""
category = serializers.SerializerMethodField() category = serializers.SerializerMethodField()
translation = serializers.SerializerMethodField()
translation = LocalizedField()
title = LocalizedField() title = LocalizedField()
title_narrator = LocalizedField() title_narrator = LocalizedField()
text = LocalizedField()
title_narrator = LocalizedField() title_narrator = LocalizedField()
class Meta: class Meta:
@ -184,11 +183,11 @@ class HadisListSerializer(serializers.ModelSerializer):
} }
return None return None
def get_translation(self, obj):
"""Get translation based on request language"""
request = self.context.get('request')
language_code = getattr(request, 'LANGUAGE_CODE', 'en')
return obj.translation.get(language_code)
# def get_translation(self, obj):
# """Get translation based on request language"""
# request = self.context.get('request')
# language_code = getattr(request, 'LANGUAGE_CODE', 'en')
# return obj.translation.get(language_code)
# def get_title(self,obj): # def get_title(self,obj):
# # ✅ Get language from request # # ✅ Get language from request

2
apps/hadis/views/hadis.py

@ -80,7 +80,7 @@ class HadisListView(ListAPIView):
# Without it, if 3 narrators are from "Layer 1", it counts as 3. # Without it, if 3 narrators are from "Layer 1", it counts as 3.
# With it, it counts as 1 (unique layer). # With it, it counts as 1 (unique layer).
layer_count=Count('transmitters__narrator_layer', distinct=True) layer_count=Count('transmitters__narrator_layer', distinct=True)
)
).select_related('category')
class HadisBasicView(RetrieveAPIView): class HadisBasicView(RetrieveAPIView):

Loading…
Cancel
Save