from django.core.management.base import BaseCommand from django.db import transaction from django.apps import apps from django.db import models as django_models class Command(BaseCommand): help = "Rename 'text' key to 'title' in all multi-language JSON fields across Hadis app models." @transaction.atomic def handle(self, *args, **options): hadis_app = apps.get_app_config('hadis') models = hadis_app.get_models() self.stdout.write("Starting key migration in JSON fields...") for model in models: json_fields = [ f.name for f in model._meta.get_fields() if isinstance(f, django_models.JSONField) ] if not json_fields: continue self.stdout.write(f"Checking model {model.__name__} for fields: {json_fields}") queryset = model.objects.all() for obj in queryset: changed = False for field in json_fields: value = getattr(obj, field) if not isinstance(value, list): continue new_list = [] field_changed = False for item in value: if isinstance(item, dict): # Check if this item follows the multi-language pattern # lang_key can be 'language_code', 'lang', or 'code' lang_val = item.get("language_code") or item.get("lang") or item.get("code") # text_val can be 'text' or 'title' text_val = item.get("text") if lang_val and text_val is not None: # We found a multi-language item with a 'text' key new_item = { "language_code": str(lang_val), "title": text_val } # Copy any other keys for k, v in item.items(): if k not in ["language_code", "lang", "code", "text", "title"]: new_item[k] = v new_list.append(new_item) field_changed = True else: new_list.append(item) else: new_list.append(item) if field_changed: setattr(obj, field, new_list) changed = True if changed: obj.save() self.stdout.write(f" Updated keys in {model.__name__} ID: {obj.id}") self.stdout.write(self.style.SUCCESS("JSON key migration completed!"))