Django model: delete() not triggered

后端 未结 5 1287
盖世英雄少女心
盖世英雄少女心 2020-11-29 23:59

I have a model:

class MyModel(models.Model):
 ...
    def save(self):
        print \"saving\"
        ...
    def delete(self):
        print \"deleting\"
          


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 00:22

    Using django v2.2.2, I solved this problem with the following code

    models.py

    class MyModel(models.Model):
        file = models.FileField(upload_to=)
    
        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()
    

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

提交回复
热议问题