|
| 1 | +from django.core.management.base import BaseCommand |
| 2 | +from django.db import transaction |
| 3 | +from django.db.models import OuterRef, Exists |
| 4 | + |
| 5 | +from osf.models import NotificationSubscription |
| 6 | + |
| 7 | + |
| 8 | +class Command(BaseCommand): |
| 9 | + help = ( |
| 10 | + 'Remove duplicate NotificationSubscription records, keeping only ' |
| 11 | + 'the highest-id record per (user, content_type, object_id, notification_type).' |
| 12 | + ) |
| 13 | + |
| 14 | + def add_arguments(self, parser): |
| 15 | + parser.add_argument( |
| 16 | + '--dry', |
| 17 | + action='store_true', |
| 18 | + help='Show how many rows would be deleted without deleting anything.', |
| 19 | + ) |
| 20 | + |
| 21 | + def handle(self, *args, **options): |
| 22 | + self.stdout.write('Finding duplicate NotificationSubscription records…') |
| 23 | + |
| 24 | + to_remove = NotificationSubscription.objects.filter( |
| 25 | + Exists( |
| 26 | + NotificationSubscription.objects.filter( |
| 27 | + user_id=OuterRef('user_id'), |
| 28 | + content_type_id=OuterRef('content_type_id'), |
| 29 | + object_id=OuterRef('object_id'), |
| 30 | + notification_type_id=OuterRef('notification_type_id'), |
| 31 | + _is_digest=OuterRef('_is_digest'), |
| 32 | + id__gt=OuterRef('id'), # keep most recent record |
| 33 | + ) |
| 34 | + ) |
| 35 | + ) |
| 36 | + |
| 37 | + count = to_remove.count() |
| 38 | + self.stdout.write(f"Duplicates to remove: {count}") |
| 39 | + |
| 40 | + if options['dry']: |
| 41 | + self.stdout.write( |
| 42 | + self.style.WARNING('Dry run enabled — no records were deleted.') |
| 43 | + ) |
| 44 | + return |
| 45 | + |
| 46 | + if count == 0: |
| 47 | + self.stdout.write(self.style.SUCCESS('No duplicates found.')) |
| 48 | + return |
| 49 | + |
| 50 | + with transaction.atomic(): |
| 51 | + deleted, _ = to_remove.delete() |
| 52 | + |
| 53 | + self.stdout.write( |
| 54 | + self.style.SUCCESS(f"Successfully removed {deleted} duplicate records.") |
| 55 | + ) |
0 commit comments