[scrobbles] Fix management command tag lookup
All checks were successful
build & deploy / test (push) Successful in 1m45s
build & deploy / deploy (push) Successful in 21s

This commit is contained in:
2026-03-24 10:58:24 -04:00
parent 125222845b
commit 6766ea7dbb

View File

@ -1,8 +1,11 @@
from django.core.management.base import BaseCommand from django.core.management.base import BaseCommand
from django.db import models
from scrobbles.models import Scrobble from scrobbles.models import Scrobble
class Command(BaseCommand): class Command(BaseCommand):
help = "Backfill tags on scrobbles from labels in their log data"
def add_arguments(self, parser): def add_arguments(self, parser):
parser.add_argument( parser.add_argument(
"--commit", "--commit",
@ -13,32 +16,34 @@ class Command(BaseCommand):
def handle(self, *args, **options): def handle(self, *args, **options):
commit = options["commit"] commit = options["commit"]
task_scrobbles = Scrobble.objects.filter(media_type=Scrobble.MediaType.TASK) scrobbles = Scrobble.objects.filter(
models.Q(log__labels__isnull=False) & ~models.Q(log__labels=[])
)
updated_count = 0 updated_count = 0
skipped_count = 0 skipped_count = 0
for scrobble in task_scrobbles: for scrobble in scrobbles:
logdata = scrobble.logdata labels = scrobble.log.get("labels", [])
if not logdata or not hasattr(logdata, "labels") or not logdata.labels: if not labels:
skipped_count += 1 skipped_count += 1
continue continue
existing_tags = list(scrobble.tags.all().values_list("name", flat=True)) existing_tags = list(scrobble.tags.all().values_list("name", flat=True))
new_labels = [ new_labels = [label for label in labels if label not in existing_tags]
label for label in logdata.labels if label not in existing_tags
]
if new_labels: if new_labels:
updated_count += 1 updated_count += 1
if commit: if commit:
for label in new_labels: for label in new_labels:
scrobble.tags.add(label) scrobble.tags.add(label)
print(f"Updated scrobble {scrobble.id} with tags: {new_labels}") self.stdout.write(
f"Updated scrobble {scrobble.id} with tags: {new_labels}"
)
else: else:
print( self.stdout.write(
f"[DRY RUN] Would update scrobble {scrobble.id} with tags: {new_labels}" f"[DRY RUN] Would update scrobble {scrobble.id} with tags: {new_labels}"
) )
print(f"\nUpdated {updated_count} scrobbles") self.stdout.write(f"\nUpdated {updated_count} scrobbles")
print(f"Skipped {skipped_count} scrobbles (no labels in logdata)") self.stdout.write(f"Skipped {skipped_count} scrobbles (no new labels)")