开发者

Does deleting a Django Model object with a File field delete the storage used for the file?

Does deleting a Django Model object with a File field delete the storage used for the file? Does it delete the file 开发者_Go百科on disk?


OMG, I sure hope not! Talk about your quick trip to the land of tears.

If you want the storage freed up then you should override the model's .delete() method, delete the file, and then super() to let the DB finish its clean up.

Update: I was wrong ... maybe. From looking at the code in django/db/fields/files.py (ver 1.1.1) I can see that under certain circumstances, depending on which storage object class you are using, it may (or may not) delete the associated storage. Unfortunately, when and why is inconsistent and there is a 2+ year old ticket open on this ambiguity. The default_storage class does delete the associated file, but not reliably (see above mentioned ticket).

This means you need to be careful and to test the specific storage class you are using before you have important data end up in an indeterminate state.


As of Django 1.3, no. From the Django 1.3 CHANGELOG:

In earlier Django versions, when a model instance containing a FileField was deleted, FileField took it upon itself to also delete the file from the backend storage. This opened the door to several data-loss scenarios, including rolled-back transactions and fields on different models referencing the same file. In Django 1.3, when a model is deleted the FileField's delete() method won't be called. If you need cleanup of 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).

Subsequent versions (I verified for 1.5) have continued the policy of leaving it as an exercise for the developer to decide when and how to delete model-associated files from storage.

A simple way to handle file deletion, if it meets your file lifetime requirements, is to catch the pre_delete signal and delete the file then. This method is compatible with bulk deletion, as is done by Django's admin.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜