我有 Book
模型。它有一些字段,如 title
、year publish
等。此外,我还覆盖了 save()
方法。添加新书时,它会检查书是否存在,并在 MEDIA_ROOT
路径中创建名称为 self.title
的新目录。
def save(self, *args, **kwargs):
book_dir = os.path.join(MEDIA_ROOT, self.title)
# check that at least one file is loading
if all([self.pdf, self.fb2, self.epub]):
raise ValidationError("At least 1 file should be uploaded!")
# create book's directory if it not exists
if os.path.exists(book_dir):
raise ValidationError("This book is already exists!")
else:
os.mkdir(book_dir)
# rename and edit storage location of books to book_dir
for field in [self.image, self.pdf, self.fb2, self.epub]:
field.storage.location = book_dir
super().save(*args, **kwargs) # Call the "real" save() method.
我还覆盖了 delete()
方法,它只删除已删除书籍的目录。
def delete(self, *args, **kwargs):
book_dir = os.path.join(MEDIA_ROOT, self.title)
rmtree(book_dir)
super().delete(*args, **kwargs) # Call the "real" delete() method.
如果我只删除一本书,delete()
方法效果很好。
但是,如果我想删除多个文件(所有操作都在管理面板中进行),只有数据库记录被删除。
所以,我想抓紧时间删除已删除图书的目录。
最佳答案
看起来 pre_delete
信号在这里很有用:https://docs.djangoproject.com/en/2.2/ref/signals/#pre-delete
关于python - 在 Django 中捕获批量事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58029435/