2 回答
TA贡献1846条经验 获得超7个赞
在post_delete信号处理程序中最容易做到这一点:
from django.core.files.storage import default_storage
@receiver(post_delete, sender=News)
def delete_associated_files(sender, instance, **kwargs):
"""Remove all files of an image after deletion."""
path = instance.thumb.name
if path:
default_storage.delete(path)
您还可以在包含文件字段的所有模型中使用 mixin 类:
from django.db.models.signals import post_delete
class FileDeletionMixin(object):
file_fields = [] # list the names of the file fields
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
post_delete.connect(delete_associated_files, sender=self.__class__,
dispatch_uid=f"_file_deletion_mixin_{self._meta.model_name}-{self._meta.app_label}")
def delete_associated_files(sender, instance, **kwargs):
"""Remove all files of an image after deletion."""
# you may want to add checks to be sure file_fields exists
# e.g. if isinstance(instance, FileDeletionMixin)
for field in instance.file_fields:
file = getattr(instance, field) # you may want to catch exception AttributeError here
if file:
file.delete(save=False)
class News(FileDeletionMixin, models.Model):
thumb = FileField # or ImageField
file_fields = ['thumb']
TA贡献1111条经验 获得超0个赞
在Django的清理包添加此功能FieldField和ImageField。
您可以使用安装它,pip install django-cleanup然后将其添加到settings.py:
INSTALLED_APPS = [
...
'django_cleanup',
...
]
添加回答
举报