我正在从表单中删除相关模型(与django admin几乎相同),我有一个项目有很多图像,图像属于Item(ForeignKey)。 我已经实现了post_delete信号来删除缩略图和从图像中删除图像/图像时的图像,问题是post_delete缩略图被删除但数据库中的图像条目仍然存在:
# Auto-delete files from filesystem when they are unneeded:
@receiver(models.signals.post_delete, sender=ImageModel)
def auto_delete_file_on_delete(sender, instance, **kwargs):
"""Deletes file from filesystem
when corresponding `ImageModel` object is deleted.
"""
if instance.imagefile:
thumbmanager = get_thumbnailer(instance.imagefile)
thumbmanager.delete()
如果我最后添加以下内容,也会删除图像实例(预期行为):
# Auto-delete files from filesystem when they are unneeded:
@receiver(models.signals.post_delete, sender=ImageModel)
def auto_delete_file_on_delete(sender, instance, **kwargs):
"""Deletes file from filesystem
when corresponding `ImageModel` object is deleted.
"""
if instance.imagefile:
thumbmanager = get_thumbnailer(instance.imagefile)
thumbmanager.delete()
instance.delete()
我错过了什么吗?删除实例后,是否应该发送post_delete信号?为什么实例在db中持久存在? 我假设这与Queryset删除行为有关,但我对此持怀疑态度,因为如果删除信号,则删除ImageModel的实例(尽管缩略图仍保留在数据库中)。 请注意,模型在ImageField字段中使用django构建,而不是简单的缩略图提供字段:
class ImageModel(models.Model):
...
imagefile = models.ImageField(upload_to="properties/%m/%Y")
item = models.ForeignKey('app.ItemModel', related_name='images')
...
上面的解决方案(instance.delete())没有任何问题,只是对行为感到好奇。
答案 0 :(得分:1)
您也可以使用django-cleanup,当您删除模型时,它会自动在FileField上调用delete方法。
pip install django-cleanup
settings.py
INSTALLED_APPS = (
...
'django_cleanup', # should go after your apps
)
答案 1 :(得分:0)
好的,它可以添加删除(保存=错误):
# These two auto-delete files from filesystem when they are unneeded:
@receiver(models.signals.post_delete, sender=ImageModel)
def auto_delete_file_on_delete(sender, instance, **kwargs):
"""Deletes file from filesystem
when corresponding `ImageModel` object is deleted.
"""
if instance.imagefile:
thumbmanager = get_thumbnailer(instance.imagefile)
thumbmanager.delete(save=False)