如何确保文件存在于Django项目中?

2 python django django-models amazon-web-services

大家好!

我的问题很简单,因为标题清楚地描述了它。

我已经FileField在某些机型上,我添加了一个属性的方法来检查文件是否存在等:

@property
def file_exists(self):
    # Because sometimes, the field may contain the string path
    # but the file doesn't exist at all in the server
    if file: # if the string path exists
        return os.path.exists(self.file.path) # If the file exists in server
Run Code Online (Sandbox Code Playgroud)

这在开发中非常有效,但是当我在AWS上迁移所有文件时,会引发错误,例如我没有这样做的权限。

我不知道这是怎么回事,还是有另一种方法来测试文件是否存在?

先感谢您!

AKX*_*AKX 6

您应该使用与存储无关的Storage.exists()方法。

存储对象FieldFile本身应该可用,所以类似

return self.file.storage.exists(self.file.name)
Run Code Online (Sandbox Code Playgroud)

应该可以。