import os from boards.abstracts.constants import FILE_DIRECTORY from django.core.management import BaseCommand from django.db import transaction from boards.models import Attachment from neboard.settings import MEDIA_ROOT __author__ = 'neko259' THUMB_SIZE = (200, 150) class Command(BaseCommand): help = 'Remove files whose models were deleted' @transaction.atomic def handle(self, *args, **options): thumb_prefix = '.{}x{}'.format(*THUMB_SIZE) count = 0 model_files = os.listdir(MEDIA_ROOT + FILE_DIRECTORY) for file in model_files: model_filename = file if thumb_prefix not in file else file.replace( thumb_prefix, '') found = Attachment.objects.filter(file=FILE_DIRECTORY + model_filename)\ .exists() if not found: print('Missing {}'.format(file)) os.remove(MEDIA_ROOT + FILE_DIRECTORY + file) count += 1 print('Deleted {} attachment files.'.format(count))