Django delete unused media files(Django 删除未使用的媒体文件)
问题描述
我有一个 django 项目,管理员可以在其中上传媒体.随着商品的销售,它们会从站点中删除,从而删除它们在 MySQL 数据库中的条目.但是,与该项目关联的图像仍保留在文件系统中.这不一定是坏行为——我不介意保留文件以防意外删除.我预见到的问题是从现在开始的两年后,由于存储空间有限,因为媒体文件夹中充斥着旧产品图片.
I have a django project in which the admins are able to upload media. As items sell, they are deleted from the site, thus removing their entry in the MySQL database. The images associated with the item, however, remain on the file system. This isn't neccessarily bad behavior - I don't mind keeping files around in case a deletion was an accident. The problem I forsee is two years from now, when storage space is limited because of a media folder bloated with old product images.
有没有人知道一种系统/编程的方式来对所有图像进行排序并将它们与相关的 MySQL 字段进行比较,从文件系统中删除任何不匹配的图像?在完美的世界中,我想象 django-admin 中的一个按钮,例如清理未使用的媒体",它执行一个能够执行此行为的 python 脚本.我将在这里分享我的最终解决方案,但我现在正在寻找的是任何有想法、了解资源或在某个时候自己做过这件事的人.
Does anyone know of a systematic/programmatic way to sort through ALL the images and compare them to the relevant MySQL fields, deleting any image which DOESN'T have a match from the filesystem? In the perfect world I'm imagining a button in the django-admin like "Clean-up unused media" which executes a python script capable of this behavior. I'll be sharing whatever my eventual solution is here, but what I'm looking for right now is anyone who has ideas, knows resources, or has done this at some point themselves.
推荐答案
试试 django-cleanup,当你删除模型时,它会自动调用 FileField 上的 delete 方法.
Try django-cleanup, it automatically invokes delete method on FileField when you remove model.
pip install django-cleanup
settings.py
settings.py
INSTALLED_APPS = (
...
'django_cleanup.apps.CleanupConfig', # should go after your apps
)
这篇关于Django 删除未使用的媒体文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Django 删除未使用的媒体文件


基础教程推荐
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01