作者在 2021-07-07 17:15:58 发布以下内容
假设startapp创建的app为app1
在app1中创建一个helpers模块,加入如下代码:
from django.db import models
from django.db.models.signals import pre_delete
from django.dispatch import receiver
def bind_delete_signal(model):
@receiver(pre_delete, sender=model)
def pre_model_delete(sender, **kwargs):
for field in sender._meta.get_fields():
if isinstance(field, models.FileField) or isinstance(field, models.ImageField):
instance = kwargs.get('instance')
getattr(instance, field.name).delete()
在apps.py中的App1Config类中重写ready方法:
def ready(self):
from app1.helpers import bind_delete_signal
for model in self.get_models():
bind_delete_signal(model)
这样,在删除模型实例的时候,只要模型实例有 FileField 和 ImageField 相关的字段,就会自动删除相关的文件