0

I am creating a cleanup script for Django Filer, so that if an image is not in use, e.g. it's not related to any other model, then I'd like to delete the image.

I can't figure out how to detect if the image is related to any other objects though. Does anybody know how to achieve this?

You can view this information when you press the delete button and are on the delete confirmation page, but I'm not sure how Django has done this.

Any help would be much appreciated.

Edit

To clarify,

from filer.models import Image

i = Image.objects.all().first()

i.get_all_related_objects.count()

The last line of the above is not valid, but this is what I'm trying to achieve, so if this is 0, then I can remove the file.

tdsymonds
  • 1,679
  • 1
  • 16
  • 26

1 Answers1

0

You can get all related objects, no matter from what related model they come, using

instance._meta.get_all_related_objects()

so when assuming you have an Image model:

for image in Image.objects.all():
    if not image._meta.get_all_related_objects():  # if this list is empty, there are no relations pointing here
        image.delete()
Nils Werner
  • 34,832
  • 7
  • 76
  • 98
  • Thanks Nils for answering so quickly but this is assuming that there is only one model (the page). I have a large number of models that could have the image linked, and it's not practical to hard code to check all the related items. Thanks – tdsymonds Jan 13 '17 at 13:34
  • My Django Filer instance doesn't have that method under "._meta", so I get the below error: 'Options' object has no attribute 'get_all_related_objects' – tdsymonds Jan 13 '17 at 13:48
  • This is an example of how I've got the instance: from filer.models import Image i = Image.objects.all().first() – tdsymonds Jan 13 '17 at 13:50