Django动态模型.FileField存储

问题描述 投票:0回答:3

我有一个这样的模型:

class Person(models.Model):
    name = models.Charfield(max_length¶=30)
    photo = models.FileField(upload_to='uploads/')

有没有办法根据

Storage
字段的值动态更改
photo
字段的
name
类?

例如,我想将姓名为

xxx
的人的照片存储到
FileSystemStorage¶
以及我想使用的其他人的照片
S3Storage

django django-models filefield
3个回答
5
投票

我也有类似的用例。使用模型字段动态更新存储

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

效果很好。


0
投票

是的,您可以为某些特定文件指定自定义上传位置。

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)

0
投票

看看这篇博文,它使用了一个名为 django-dynamic-storage 的包,可以很好地处理您的用例

© www.soinside.com 2019 - 2024. All rights reserved.