Django 删除未使用的媒体文件 [英] Django delete unused media files

查看:25
本文介绍了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 删除未使用的媒体文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆