Tuesday, June 29, 2021

Django Model How to have a hook to deletion of the model

For the DefaultAdminSite the delete_queryset is called if the user has the correct permissions, the only difference is that the original function calls queryset.delete() which doesn't trigger the model delete method. This is less efficient since is not a bulk operation anymore, but it keeps the filesystem clean.


Below are example Model and ModelAdmins 


models.py

class MyModel(models.Model):

    file = models.FileField(upload_to=<path>)


    def save(self, *args, **kwargs):

        if self.pk is not None:

            old_file = MyModel.objects.get(pk=self.pk).file

            if old_file.path != self.file.path:

                self.file.storage.delete(old_file.path)


        return super(MyModel, self).save(*args, **kwargs)


    def delete(self, *args, **kwargs):

        ret = super(MyModel, self).delete(*args, **kwargs)

        self.file.storage.delete(self.file.path)

        return ret

admin.py

class MyModelAdmin(admin.ModelAdmin):


    def delete_queryset(self, request, queryset):

        for obj in queryset:

            obj.delete()


References:

https://stackoverflow.com/questions/1471909/django-model-delete-not-triggered

No comments:

Post a Comment