Override django's model delete method for bulk deletion

前端 未结 3 676
无人共我
无人共我 2020-12-08 07:51

I\'m overriding Django\'s model delete method in order to delete orphan files in the disk for image fields, something like this:

class Image(models.Model):
          


        
3条回答
  •  萌比男神i
    2020-12-08 08:16

    Delete method of queryset works directly on the database. It does not call Model.delete() methods. From the docs:

    Keep in mind that this will, whenever possible, be executed purely in SQL, and so the delete() methods of individual object instances will not necessarily be called during the process. If you’ve provided a custom delete() method on a model class and want to ensure that it is called, you will need to “manually” delete instances of that model (e.g., by iterating over a QuerySet and calling delete() on each object individually) rather than using the bulk delete() method of a QuerySet.

    If you want to override Django administration interface's default behavior, you can write a custom delete action:

    https://docs.djangoproject.com/en/1.7/ref/contrib/admin/actions/

    Another method is to override post_delete (or pre_delete) signal instead of delete method:

    https://docs.djangoproject.com/en/1.7/ref/signals/#django.db.models.signals.post_delete

    Like pre_delete, but sent at the end of a model’s delete() method and a queryset’s delete() method.

提交回复
热议问题