Guest User

Untitled

a guest
Feb 23rd, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. import os
  2.  
  3. from django.core.management.base import BaseCommand
  4. from django.apps import apps
  5. from django.db.models import Q
  6. from django.conf import settings
  7. from django.db.models import FileField
  8.  
  9.  
  10. class Command(BaseCommand):
  11. help = "Este comando borra ficheros de MEDIA_ROOT que ya no están referenciados por nungún modelo.
  12.  
  13. def handle(self, *args, **options):
  14. all_models = apps.get_models()
  15. physical_files = set()
  16. db_files = set()
  17.  
  18. # Get all files from the database
  19. for model in all_models:
  20. file_fields = []
  21. filters = Q()
  22. for f_ in model._meta.fields:
  23. if isinstance(f_, FileField):
  24. file_fields.append(f_.name)
  25. is_null = {'{}__isnull'.format(f_.name): True}
  26. is_empty = {'{}__exact'.format(f_.name): ''}
  27. filters &= Q(**is_null) | Q(**is_empty)
  28. # only retrieve the models which have non-empty, non-null file fields
  29. if file_fields:
  30. files = model.objects.exclude(filters).values_list(*file_fields, flat=True).distinct()
  31. db_files.update(files)
  32.  
  33. # Get all files from the MEDIA_ROOT, recursively
  34. media_root = getattr(settings, 'MEDIA_ROOT', None)
  35. if media_root is not None:
  36. for relative_root, dirs, files in os.walk(media_root):
  37. for file_ in files:
  38. # Compute the relative file path to the media directory, so it can be compared to the values from the db
  39. relative_file = os.path.join(os.path.relpath(relative_root, media_root), file_)
  40. physical_files.add(relative_file)
  41.  
  42. # Compute the difference and delete those files
  43. deletables = physical_files - db_files
  44. if deletables:
  45. for file_ in deletables:
  46. os.remove(os.path.join(media_root, file_))
  47.  
  48. # Bottom-up - delete all empty folders
  49. for relative_root, dirs, files in os.walk(media_root, topdown=False):
  50. for dir_ in dirs:
  51. if not os.listdir(os.path.join(relative_root, dir_)):
  52. os.rmdir(os.path.join(relative_root, dir_))
Add Comment
Please, Sign In to add comment