6

I have a model like this:

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

Is there any way to dynamically change the Storage class of photo field based on the value of the name field?

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

2 Answers 2

5

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

It worked fine.

Sign up to request clarification or add additional context in comments.

Comments

0

Yes, You can assign custom upload location for some specific 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)

3 Comments

thanks, but I want to change the storage type. for example, some files have to store in hard disk and the others should store in amazon s3 bucket
sorry @HasanRamezani i have no idea how to do that.
@HasanRamezani were you able to solve this ? I also have a similar use case. I am unable to find how can I do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.