Skip to content

Instantly share code, notes, and snippets.

@manthey
Created March 8, 2023 18:41
Show Gist options
  • Save manthey/ba9a76c86691d39e46e4a020bdf6092c to your computer and use it in GitHub Desktop.
Save manthey/ba9a76c86691d39e46e4a020bdf6092c to your computer and use it in GitHub Desktop.
import os
from collections import defaultdict
import configurations.importer
import django
from django.apps import apps
from django.db import models
os.environ['DJANGO_SETTINGS_MODULE'] = 'shapeworks_cloud.settings'
os.environ.setdefault('DJANGO_CONFIGURATION', 'DevelopmentConfiguration')
configurations.importer.install(check_options=True)
django.setup()
model_dict = defaultdict(list)
for model in apps.get_models():
for field in model._meta.fields:
if issubclass(field.__class__, models.FileField):
model_dict[model].append(field)
referenced = set()
for model in model_dict:
all = model.objects.all().iterator()
for object in all:
for field in model_dict[model]:
target_file = getattr(object, field.name)
if target_file:
referenced.add(target_file.name)
print('Found %d referenced files' % len(referenced))
base = '/data/django-storage/'
for root, _dirs, files in os.walk(base):
for file in files:
path = os.path.join(base, root, file)
subpath = path[len(base):]
if subpath not in referenced:
print('removing %s' % path)
os.unlink(path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment