2 changed files with 67 additions and 7 deletions
@ -0,0 +1,65 @@ |
|||
from django.core.management.base import BaseCommand |
|||
from django.apps import apps |
|||
from django.db import models |
|||
|
|||
class Command(BaseCommand): |
|||
help = "Populate missing 'en' translations with other available language data for JSONFields" |
|||
|
|||
def handle(self, *args, **options): |
|||
target_app_labels = ['course', 'quiz', 'blog', 'hadis', 'library'] |
|||
updated_records = 0 |
|||
|
|||
for app_label in target_app_labels: |
|||
try: |
|||
app_config = apps.get_app_config(app_label) |
|||
except LookupError: |
|||
continue |
|||
|
|||
for model in app_config.get_models(): |
|||
json_fields = [f for f in model._meta.get_fields() if isinstance(f, models.JSONField)] |
|||
if not json_fields: |
|||
continue |
|||
|
|||
for instance in model.objects.all(): |
|||
changed = False |
|||
for field in json_fields: |
|||
val = getattr(instance, field.name) |
|||
|
|||
if isinstance(val, list): |
|||
has_en = False |
|||
fallback_text = None |
|||
|
|||
valid = True |
|||
for item in val: |
|||
if not isinstance(item, dict) or 'language_code' not in item or 'title' not in item: |
|||
valid = False |
|||
break |
|||
|
|||
title_val = item.get('title') |
|||
if isinstance(title_val, str): |
|||
title_str = title_val.strip() |
|||
elif title_val is not None: |
|||
title_str = str(title_val).strip() |
|||
else: |
|||
title_str = '' |
|||
|
|||
if item.get('language_code') == 'en' and title_str: |
|||
has_en = True |
|||
elif title_str: |
|||
if not fallback_text: |
|||
fallback_text = title_val |
|||
|
|||
if valid and not has_en and fallback_text: |
|||
val.append({ |
|||
"language_code": "en", |
|||
"title": fallback_text |
|||
}) |
|||
setattr(instance, field.name, val) |
|||
changed = True |
|||
|
|||
if changed: |
|||
instance.save() |
|||
updated_records += 1 |
|||
self.stdout.write(f"Updated {model.__name__} ID {instance.pk}") |
|||
|
|||
self.stdout.write(self.style.SUCCESS(f"Finished updating {updated_records} records.")) |
|||
Write
Preview
Loading…
Cancel
Save
Reference in new issue