python - 在 Django 中捕获批量事件

标签 python mysql django

我有 Book 模型。它有一些字段,如 titleyear 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/

相关文章:

python - 在 python 中使用 "in"匹配整个单词

php - 为什么我收到此错误,一切看起来都正确 : "Undefined index"?

python - Django 不考虑夏令时

python - IntegrityError : (1062, key 条目重复)

javascript - react 错误 : Target Container is not a DOM Element

python - 使用 Python 执行多个 adb shell 命令

python - NodeJS - SocketIO over SSL with websocket transport

python - 在不加载 CSV 的情况下将标题添加到 CSV

MYSQL JOIN - 范围

mysql - 使用 4.1.1 之前的身份验证协议(protocol)通过 R 访问 MySQL