Skip to content

Commit 1c919e0

Browse files
committed
gwy: normalize dataset authors format on save + add migration command
1 parent 7733b13 commit 1c919e0

2 files changed

Lines changed: 136 additions & 0 deletions

File tree

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
"""Convert dataset authors from old string format to new object format.
2+
3+
Old format: ["Author One", "Author Two"] (list of strings)
4+
New format: [{"name": "Author One", "orcid_id": ""}, ...] (list of dicts)
5+
6+
This is a one-time data fix for datasets that were created or versioned
7+
before the model-level auto-normalization was added to Dataset.save().
8+
"""
9+
10+
from django.core.management.base import BaseCommand
11+
from loguru import logger
12+
13+
from sds_gateway.api_methods.models import Dataset
14+
15+
16+
class Command(BaseCommand):
17+
help = (
18+
"Convert dataset authors from old string format ['Name'] "
19+
"to new object format [{'name': 'Name', 'orcid_id': ''}]"
20+
)
21+
22+
def add_arguments(self, parser):
23+
parser.add_argument(
24+
"--dry-run",
25+
action="store_true",
26+
help="Only count affected datasets without modifying them",
27+
)
28+
parser.add_argument(
29+
"--uuid",
30+
type=str,
31+
help="Migrate only a specific dataset by UUID",
32+
)
33+
34+
def handle(self, *args, **options):
35+
dry_run = options["dry_run"]
36+
specific_uuid = options.get("uuid")
37+
38+
# Query datasets with non-empty authors
39+
queryset = Dataset.objects.filter(authors__isnull=False).exclude(authors="")
40+
if specific_uuid:
41+
queryset = queryset.filter(uuid=specific_uuid)
42+
43+
total = queryset.count()
44+
updated = 0
45+
skipped = 0
46+
errors = 0
47+
48+
self.stdout.write(f"Scanning {total} dataset(s) with authors...")
49+
50+
for dataset in queryset:
51+
try:
52+
# from_db already deserialized authors from JSON string to Python object
53+
authors = dataset.authors
54+
55+
# Skip if not a list
56+
if not isinstance(authors, list):
57+
skipped += 1
58+
continue
59+
60+
# Skip empty lists
61+
if not authors:
62+
skipped += 1
63+
continue
64+
65+
# Skip if already in new format (list of dicts with 'name' key)
66+
if isinstance(authors[0], dict):
67+
skipped += 1
68+
continue
69+
70+
# Convert old format: list of strings → list of dicts
71+
if isinstance(authors[0], str):
72+
new_authors = [
73+
{"name": author, "orcid_id": ""}
74+
for author in authors
75+
if isinstance(author, str)
76+
]
77+
78+
if not new_authors:
79+
logger.warning(
80+
f"Dataset {dataset.uuid}: no valid author strings found, "
81+
"skipping",
82+
)
83+
skipped += 1
84+
continue
85+
86+
if dry_run:
87+
logger.info(
88+
f"[DRY-RUN] Would convert dataset {dataset.uuid}: "
89+
f"{len(authors)} author(s) in old format"
90+
)
91+
else:
92+
dataset.authors = new_authors
93+
dataset.save(update_fields=["authors"])
94+
logger.info(
95+
f"Converted dataset {dataset.uuid}: "
96+
f"{len(authors)} author(s) → new format"
97+
)
98+
updated += 1
99+
else:
100+
# Unexpected format
101+
logger.warning(
102+
f"Dataset {dataset.uuid}: unexpected author type "
103+
f"{type(authors[0]).__name__}, skipping"
104+
)
105+
skipped += 1
106+
107+
except Exception as e: # noqa: BLE001 # intentional: continue processing remaining datasets
108+
logger.error(f"Error processing dataset {dataset.uuid}: {e}")
109+
errors += 1
110+
111+
self.stdout.write(
112+
f"Done: {updated} updated, {skipped} skipped, {errors} errors"
113+
+ (" (dry run)" if dry_run else "")
114+
)

‎gateway/sds_gateway/api_methods/models.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -990,6 +990,28 @@ def save(self, *args, **kwargs) -> None:
990990
field_value = getattr(self, field)
991991
if field_value:
992992
if isinstance(field_value, list):
993+
# --- Authors format normalization ---
994+
# Prevent "authors still in old string format" warning by
995+
# auto-converting old-style list-of-strings to list-of-dicts
996+
# on save. Catches all write paths (form, versioning, API,
997+
# direct ORM create) so old format cannot persist even when
998+
# entering through code paths that bypass form validation
999+
# (e.g. dataset versioning which copies raw field values
1000+
# via getattr + Dataset.objects.create).
1001+
#
1002+
# Old format: ["Author One", "Author Two"]
1003+
# New format: [{"name": "Author One", "orcid_id": ""}, ...]
1004+
if (
1005+
field == "authors"
1006+
and field_value
1007+
and isinstance(field_value[0], str)
1008+
):
1009+
field_value = [
1010+
{"name": author, "orcid_id": ""}
1011+
for author in field_value
1012+
if isinstance(author, str)
1013+
]
1014+
# --- End authors format normalization ---
9931015
setattr(self, field, json.dumps(field_value))
9941016
elif isinstance(field_value, str):
9951017
# If it's already a string, it might be JSON - try to parse it

0 commit comments

Comments
 (0)