Django动态模型。FileField存储 [英] Django dynamic models.FileField Storage
问题描述
我有一个这样的模型:
class Person(models.Model):
name = models.Charfield(max_length¶=30)
photo = models.FileField(upload_to='uploads/')
是否有任何方法可以根据<$ c的值动态更改照片
字段的 Storage
类c $ c> name 字段?
Is there any way to dynamically change the Storage
class of photo
field based on the value of the name
field?
例如,我要存储名称为的人的照片xxx
到FileSystemStorage¶
,对于其他我想使用 S3Storage
for example, I want to store the photo of the persons with the name xxx
to FileSystemStorage¶
and for the others I want to use S3Storage
推荐答案
我也有一个类似的用例。使用模型字段 object_storage_name
动态更新存储。
通过从文章 https://medium.com/@hiteshgarg14/how-to-dynamic-selectly-storage-in-django-filefield-bc2e8f5883fd
I also had a similar use case. Update storage dynamically using the model field object_storage_name
.
Tried this below code by taking inspiration from the article 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
效果很好。
这篇关于Django动态模型。FileField存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!