我有一个这样的模型:
class Person(models.Model):
name = models.Charfield(max_length¶=30)
photo = models.FileField(upload_to='uploads/')
有没有办法根据
Storage
字段的值动态更改 photo
字段的 name
类?
例如,我想将姓名为
xxx
的人的照片存储到 FileSystemStorage¶
以及我想使用的其他人的照片 S3Storage
我也有类似的用例。使用模型字段动态更新存储
object_storage_name
。
从文章https://medium.com/@hiteshgarg14/how-to-dynamically-select-storage-in-django-filefield-bc2e8f5883fd中汲取灵感,尝试了下面的代码
class MediaDocument(models.Model):
object_storage_name = models.CharField(max_length=255, null=True)
file = DynamicStorageFileField(upload_to=mediadocument_directory_path)
class DynamicStorageFieldFile(FieldFile):
def __init__(self, instance, field, name):
super(DynamicStorageFieldFile, self).__init__(
instance, field, name
)
if instance.object_storage_name == "alibaba OSS":
self.storage = AlibabaStorage()
else:
self.storage = MediaStorage()
class DynamicStorageFileField(models.FileField):
attr_class = DynamicStorageFieldFile
def pre_save(self, model_instance, add):
if model_instance.object_storage_name == "alibaba OSS":
storage = AlibabaStorage()
else:
storage = MediaStorage()
self.storage = storage
model_instance.file.storage = storage
file = super(DynamicStorageFileField, self
).pre_save(model_instance, add)
return file
效果很好。
是的,您可以为某些特定文件指定自定义上传位置。
def my_upload_function(instance, filename):
if instance.name === your_name:
return your_location
return generic_location
class Person(models.Model):
name = models.Charfield(max_length¶=30)
photo = models.FileField(upload_to=my_upload_function)
看看这篇博文,它使用了一个名为 django-dynamic-storage 的包,可以很好地处理您的用例