django - 如何在 django 信号中取消删除

标签 django django-signals

有没有办法使用 django pre_delete 信号取消记录的删除?

例子:

def on_delete(sender,**kwargs):
  if not <some condition>:
    #cancel the deletion
 # else continue with the deletion
pre_delete.connect(on_delete,sender=MyModel)

另一个问题是有一种方法可以告诉模型“ 在更改文件之前先删除原始文件 ” 因为现在这就是我所做的(见下面的代码),我不确定这是最好的方法。
def on_save(sender,**kwargs):
  obj = kwargs['instance']
  try:
    id = obj.pk
    # find the file
    original_file = sender.objects.get(pk=id)
    # delete the original file before uploading a new file
    original_file.file.delete()
  except ....

pre_save.connect(on_save,sender=ModelWithFileUpload)

(在 django 1.2 中,他们会在更改或删除时自动删除文件,但在 django 1.3 中,他们删除了此功能)

提前致谢

最佳答案

我会尝试一些小技巧:

def on_delete(sender,**kwargs):
  if not <some condition>:
    raise Exception('Do not delete')#cancel the deletion
 # else continue with the deletion
pre_delete.connect(on_delete,sender=MyModel)

和 View
def on_save(sender,**kwargs):
  obj = kwargs['instance']
  try:
    id = obj.pk
    # find the file
    original_file = sender.objects.get(pk=id)
    # delete the original file before uploading a new file
  except ... :
    # oder exceptions 

  try:
    original_file.file.delete()
  except:
    pass #not deleted

pre_save.connect(on_save,sender=ModelWithFileUpload)

在信号中引发异常应该停止 delete() 方法的执行,同时将异常返回到它被调用的地方。您可以创建自己的 Exception 子类,以仅排除某些类型的异常(您几乎不应该使用 except 不带参数)。

关于django - 如何在 django 信号中取消删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5624439/

相关文章:

sql - django 信号 vs 触发器?

python - 在 django 1.8 中,如何在设置自定义用户模型时为 post_migrate 和 post_syncdb 信号接收器设置发送方?

django-social-auth 不正确的身份验证服务

python - 如何从 Django 中的 ModelForm 手动创建选择字段?

python - 导入错误 : DLL load failed : - when trying to import psycopg2 library

django - 重新定义AppConfig.ready()

Django 排除模型发送信号

Django:删除多对多的一侧时没有 m2m_changed 信号?

python - 在 Python 中剥离服务器端注释

Django 自定义命令未显示在 Heroku 上