gpt4 book ai didi

django - 覆盖 django 的模型删除方法进行批量删除

转载 作者:行者123 更新时间:2023-12-03 13:18:08 31 4
gpt4 key购买 nike

我正在覆盖 Django 的模型删除方法,以便删除磁盘中图像字段的孤立文件,如下所示:

class Image(models.Model):
img = models.ImageField(upload_to=get_image_path)
...
def delete(self, *args, **kwargs):
self.img.delete()
super(Image, self).delete(*args, **kwargs)

当我从管理员中删除单个对象时,这很好用,但是当我选择多个对象并删除它们时,这似乎没有被调用。我已经在谷歌上搜索了一段时间,但没有找到正确的关键字来获得答案,官方文档似乎也没有谈论这个主题。

最佳答案

It does :

The delete() method does a bulk delete and does not call any delete() methods on your models. It does, however, emit the pre_delete and post_delete signals for all deleted objects (including cascaded deletions).



为此,您可以覆盖 QuerySet 上的删除方法,然后应用该 QuerySet作为经理:
class ImageQuerySet(models.QuerySet):

def delete(self, *args, **kwargs):
for obj in self:
obj.img.delete()
super(ImageQuerySet, self).delete(*args, **kwargs)

class Image(models.Model):
objects = ImageQuerySet.as_manager()
img = models.ImageField(upload_to=get_image_path)
...
def delete(self, *args, **kwargs):
self.img.delete()
super(Image, self).delete(*args, **kwargs)

关于django - 覆盖 django 的模型删除方法进行批量删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28896237/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com