tags:

views:

86

answers:

2

The following works great when going to the objects adminpage and select delete. The problem is that when using multiselect and deleting multiple items at once it doesn't use my delete-override. I've been looking for a solution but haven't found one so it's time to turn to the masters ;)

class Photo(models.Model):
    name = models.CharField(max_length=256, unique=True)
    slug = models.SlugField(unique=True)
    image = models.ImageField(upload_to='photos/')

    def delete(self):
        super(Photo, self).delete()
        ### Check if the dir is empty, then remove the folder
        ph = Photo.objects.filter(album=self.album)
        if ph.count() == 0:
            rmtree(os.path.join(settings.MEDIA_ROOT, 'photos/' + self.album.slug))     
A: 

when using multiselect and deleting multiple items at once

I suspect this means you're doing something like:

Photo.objects.filter(name='something').delete()

If that's the case, that will not call your custom delete method since it uses the delete method on a queryset. While not very efficient, you can force your delete method to be called by:

for photo in Photo.objects.filter(name='something'):
    photo.delete()
brianz
I'll try and override the queryset delete-method and use that to run my custom delete-function.
xintron
A: 

Solved my problem :)

class PhotoQuerySet(QuerySet):
    def delete(self):
        for x in self:
            x.delete()

class PhotoManager(models.Manager):
    def get_query_set(self):
        return PhotoQuerySet(self.model)

class Photo(models.Model):
    name = models.CharField(max_length=256, unique=True)
    slug = models.SlugField(unique=True)
    image = models.ImageField(upload_to='photos/')

    objects = PhotoManager()

    def delete(self):
        os.remove(self.get_thumbnail_name())
        os.remove(self.get_medium_name())
        super(Photo, self).delete()
xintron