Delete Django ImageField and FileField records whose files are not found on the server

I've recently lost some files in my media folder, and I want to delete the image field/FileField objects whose files have been removed, across all models of my application.

I've tried django-cleanup, but it appears to be doing the inverse operation, i.e. deleting files on the server whose objects have been removed from the database.


You can write a management command for this, here is a way how to handle this

Class cleanup(BaseCommand):
    def handle(self,options):
         for obj in Files.objects.all():
             if os.path.exists(settings.MEDIA_DIR+ obj.filename): continue
             obj.delete()

Note that a FileField will be falsy if the file is not there, so you can use this simple solution:

for instance in ModelWithFileField.objects.all():
    if bool(instance.file_field):
        continue
    instance.delete()

You can even do it in a django shell, so you do not have to write a script for it.