7

I have the following code to delete a file:

from django.db import models
from django import forms
import os

class Document(models.Model):
    docfile = models.FileField(upload_to='documents/%Y/%m/%d')
    def __unicode__(self):
        return '%s' % (self.docfile.name)
    def delete(self, *args, **kwargs):
        os.rmdir(os.path.join(settings.MEDIA_ROOT, self.docfile.name))
        super(Document,self).delete(*args,**kwargs)

It manages to delete the objects I ask it to in my views.py but when I reupload a file of the same name it seems as though the original file still exists since I'll get "output_1.txt" instead of "output.txt".

This is the code I use to delete:

def delete_matrix():
    documents = Document.objects.all()
    documents.delete()

Am I not deleting the file from the database? Any help would be appreciated.

4

4 回答 4

11

您的问题是您正在覆盖delete()模型上的方法,但您正在调用默认管理器()返回的delete方法。这些是 2 种不同的方法,因此有 2 种方法可以解决此问题。QuerySetDocuments.object.all().delete()

1.在delete模型的方法中,替换行

os.rmdir(os.path.join(settings.MEDIA_ROOT, self.docfile.name))

经过

os.remove(os.path.join(settings.MEDIA_ROOT, self.docfile.name))

并且,分别为每个对象调用删除方法。代替

Document.objects.all().delete()

documents = Document.objects.all()
for document in documents:
    document.delete()

2.替换默认管理器以返回一个QuerySet覆盖该delete()方法的自定义。这在 Django中的覆盖中进行了解释QuerySet.delete()

于 2013-07-15T21:34:00.063 回答
0

尝试这个

document = Document.objects.get(pk=pk)
# if `save`=True, changes are saved to the db else only the file is deleted
document.docfile.delete(save=True)
于 2019-10-28T22:11:49.077 回答
0

您可以使用更简单的代码:

def delete(self, *args, **kwargs):
    if self.docfile:
        self.docfile.delete()
    super().delete(*args, **kwargs)
于 2021-10-01T14:22:57.407 回答
0

这是另一个解决方案

def delete(self, *args, **kwargs):
   os.remove(os.path.join(settings.MEDIA_ROOT, self.qr_code.name))
   super().delete(*args, **kwargs)

于 2020-09-18T08:38:49.033 回答