from django.core.management.base import BaseCommand from django.db import transaction from apps.video.models import VideoCategory, VideoCollection, VideoPlaylist, PlaylistItem class Command(BaseCommand): help = 'Delete all data from VideoCategory, VideoCollection, and VideoPlaylist (keeps Video model data)' def add_arguments(self, parser): parser.add_argument( '--confirm', action='store_true', help='Confirm deletion without prompting' ) def handle(self, *args, **options): confirm = options.get('confirm', False) # Count current data category_count = VideoCategory.objects.count() collection_count = VideoCollection.objects.count() playlist_count = VideoPlaylist.objects.count() playlist_item_count = PlaylistItem.objects.count() self.stdout.write(self.style.WARNING('\n=== Current Data Count ===')) self.stdout.write(f'VideoCategory: {category_count}') self.stdout.write(f'VideoCollection: {collection_count}') self.stdout.write(f'VideoPlaylist: {playlist_count}') self.stdout.write(f'PlaylistItem: {playlist_item_count}') self.stdout.write(self.style.WARNING('\n=== Video Data Will NOT Be Deleted ===\n')) if not confirm: user_input = input('Are you sure you want to delete this data? Type "yes" to confirm: ') if user_input.lower() != 'yes': self.stdout.write(self.style.ERROR('Operation cancelled.')) return try: with transaction.atomic(): # Delete in order to respect foreign key constraints # 1. Delete PlaylistItem first (references VideoPlaylist) deleted_playlist_items = PlaylistItem.objects.all().delete() self.stdout.write(self.style.SUCCESS(f'✓ Deleted {deleted_playlist_items[0]} PlaylistItems')) # 2. Delete VideoPlaylist (may reference VideoCategory and VideoCollection through M2M) deleted_playlists = VideoPlaylist.objects.all().delete() self.stdout.write(self.style.SUCCESS(f'✓ Deleted {deleted_playlists[0]} VideoPlaylists')) # 3. Delete VideoCollection deleted_collections = VideoCollection.objects.all().delete() self.stdout.write(self.style.SUCCESS(f'✓ Deleted {deleted_collections[0]} VideoCollections')) # 4. Delete VideoCategory deleted_categories = VideoCategory.objects.all().delete() self.stdout.write(self.style.SUCCESS(f'✓ Deleted {deleted_categories[0]} VideoCategories')) self.stdout.write(self.style.SUCCESS('\n✓ All data deleted successfully!')) except Exception as e: self.stdout.write(self.style.ERROR(f'\n✗ Error during deletion: {str(e)}')) raise