【问题标题】:Django dynamic models.FileField StorageDjango 动态模型.FileField 存储
【发布时间】:2018-11-08 15:24:51
【问题描述】:

我有一个这样的模型:

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

有没有办法根据name字段的值动态改变photo字段的Storage类?

例如,我想将名称为xxx 的人的照片存储到FileSystemStorage¶,而其他人我想使用S3Storage

【问题讨论】:

    标签: django django-models filefield


    【解决方案1】:

    我也有类似的用例。使用模型字段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
    

    效果很好。

    【讨论】:

      【解决方案2】:

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

      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)
      

      【讨论】:

      • 谢谢,但我想更改存储类型。例如,有些文件必须存储在硬盘中,而其他文件应该存储在 amazon s3 存储桶中
      • 对不起@HasanRamezani 我不知道该怎么做。
      • @HasanRamezani 你能解决这个问题吗?我也有类似的用例。我无法找到我该怎么做。
      猜你喜欢
      • 2013-07-06
      • 1970-01-01
      • 1970-01-01
      • 2018-11-08
      • 1970-01-01
      • 1970-01-01
      • 2018-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多