Does the Django model object with the File field delete the repository used for the file?

Does the Django Model object with the File field delete the storage used for the file? Does the file delete on disk?

+4
source share
2 answers

OMG, I hope not! Tell us about your quick trip to the country of tears.

If you want the storage to be freed, you must override the .delete () model method, delete the file, and then super () so that the DB completes the cleanup.

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

This means that you need to be careful and test the specific storage class that you use before important data gets into an undefined state.

+5
source

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

In earlier versions of Django, when the model instance containing FileField was deleted, FileField also took over the deletion of the file from internal storage. This opened the door to several data loss scenarios, including rollback transactions and fields on different models that reference the same file. In Django 1.3, when you delete a model, the FileField delete () method will not be called. If you need to clean up lost files, you will need to process it yourself (for example, using a special management command that you can run manually or schedule periodically, for example, cron).

Subsequent versions (I checked for 1.5) continued the policy of leaving it as an exercise for the developer to decide when and how to remove model-related files from the repository.

An easy way to handle file deletion, if it meets your file life cycle requirements, is then to catch the pre_delete signal and delete the file . This method is compatible with bulk deletion, as the Django administrator does.

+4
source

All Articles