Django删除Model时自动删除文件
source link: https://note.qidong.name/2019/11/django-delete-file/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Django删除Model时自动删除文件
2019-11-04 21:14:10 +08 字数:400 标签: Django
默认情况下,Django的Model在删除时,不会删除FileField
或ImageField
所代表的文件。
Note that when a model is deleted, related files are not deleted. If you need to cleanup orphaned files, you’ll need to handle it yourself (for instance, with a custom management command that can be run manually or scheduled to run periodically via e.g. cron).
如果有这个需求,比如要控制服务器的硬盘占用,则需要在删除前后使用一些手段。
Django REST Framework ¶
利用Django REST Framework中的ViewSet
,可以实现在删除前插入预处理操作。
class MyModelViewSet(ModelViewSet):
queryset = MyModel.objects.all().order_by('-date_created')
serializer_class = MyModelSerializer
def perform_destroy(self, instance):
instance.file.delete(save=False)
instance.delete()
但这样做的问题是,在连锁删除时,会有遗漏。 它只是在REST API层面做了删除的预处理,如果不走API,则删除不会执行这一句。
利用signals ¶
稳妥的做法,是利用signals,比如pre_delete
或post_delete
,在删除前后做处理。
from django.db.models.signals import pre_delete
@receiver(pre_delete, sender=MyModel)
def handle_camera_deleted(instance: MyModel, **_):
instance.file.delete(save=False)
另外,对django-storages这样的远程文件来说,删除本地文件的同时就能删除远程文件。
参考 ¶
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可,详见本站版权声明。
本站没有任何支持评论功能的计划。 如果你对本站的设计、内容、观点有什么意见,欢迎来信指正。
作者:匿蟒 邮箱:[email protected] 备案:闽ICP备15022549号
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK