简体   繁体   English

在Django中未调用自定义存储delete()方法

[英]Custom Storage delete() method is not called in Django

I have a field that inherits from ImageField with a custom storage like this: 我有一个从ImageField继承自定义存储的字段,如下所示:

image = PicasaImageField(upload_to=get_upload_to, blank=True, storage=pwcs())

When deleting an object with this field (using object.delete(), NOT bulk), the delete method of the custom storage doesn't get called. 删除带有此字段的对象时(使用object.delete(),不是大容量),不会调用自定义存储的delete方法。 Trying to debug, I couldn't find where Django is going through the fields of an object to delete the file or whatever is behind in the actual storage. 尝试进行调试时,我找不到Django正在通过对象的字段删除文件的位置或实际存储中的任何内容。 Or should I delete the file manually / in a hook / write a custom delete() method into my end model that will call the behind-the-stage delete() on the actual object? 还是应该手动删除文件/挂钩/将自定义delete()方法写入我的最终模型,该模型将在实际对象上调用后台的delete()? I failed to find how this is handled with the standard ImageFile + default filesystem, but would assume regular files would be deleted. 我无法找到标准ImageFile +默认文件系统如何处理此问题,但是假定常规文件将被删除。 Or am I getting it wrong? 还是我弄错了?

Thanks for any insights. 感谢您的任何见解。

Igor 伊戈尔

From the Django 1.3 release notes : Django 1.3发行说明中

when a model is deleted the FileField's delete() method won't be called. 删除模型时,不会调用FileField的delete()方法。 If you need cleanup of orphaned files, you'll need to handle it yourself 如果需要清理孤立的文件,则需要自己处理

As you suggested you could handle this in a custom delete method: 如您所建议,您可以使用自定义删除方法处理此问题:

def delete(self, *args, **kwargs):
    image.delete(save=False)
    super(Foo, self).delete(*args, **kwargs)

or use a receiver function which will be called even when object.delete() is not called: 或使用即使未调用object.delete()也会被调用的接收器函数:

@receiver(post_delete, sender=Foo, weak=False)
def delete_image_on_file(sender, instance, **kwargs):
    image.delete(save=False)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM