migrate_scrobble_log_to_json.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from django.core.management.base import BaseCommand
  2. from scrobbles.models import Scrobble
  3. class Command(BaseCommand):
  4. def add_arguments(self, parser):
  5. parser.add_argument(
  6. "--commit",
  7. action="store_true",
  8. help="Actually migrate data",
  9. )
  10. def handle(self, *args, **options):
  11. dry_run = True
  12. if options["commit"]:
  13. dry_run = False
  14. scrobbles_with_logs = (
  15. Scrobble.objects.filter(scrobble_log__isnull=False)
  16. .exclude(scrobble_log="")
  17. .exclude(scrobble_log="\n")
  18. )
  19. updated_scrobble_count = 0
  20. for scrobble in scrobbles_with_logs:
  21. if "\n" in scrobble.scrobble_log:
  22. lines = scrobble.scrobble_log.split("\n")
  23. else:
  24. lines = [scrobble.scrobble_log]
  25. old_data = {}
  26. for line_num, line in enumerate(lines):
  27. if line_num == 0 or line == "":
  28. continue
  29. old_data[str(line_num)] = line
  30. if old_data:
  31. scrobble.scrobble_log = {"legacy_data": old_data}
  32. updated_scrobble_count += 1
  33. if not dry_run:
  34. scrobble.save(update_fields=["scrobble_log"])
  35. else:
  36. print(
  37. f"Scrobble {scrobble} scrobble_log updated to {old_data}"
  38. )
  39. print(f"Migrated scrobble logs for {updated_scrobble_count} scrobbles")