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中从Azure BLOB存储中读取文件 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 包装空间模型 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
