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

Time:01-23

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.

CodePudding user response:

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()

CodePudding user response:

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.

  •  Tags:  
  • Related