0

Let's say I have a model somewhat like this -

class Test(models.Model):
    some_file=FileField(upload_to='test_directory')

class TestTransfer(models.Model):
    transferred_file=FileField(upload_to='transfer_directory')

Now, I have already tried simple object to object copying like this:

transfer_object.transferred_file=test_object.some_file
transfer_object.save()

What the above code does not do is, it does not upload the file to transfer_directory. Since the file is huge, I don't want it to take up memory space and there are multiple files which I have to transfer.

I am using S3 as media storage if that's needed.

If there is some work around this problem, I would be content

yadavankit
  • 353
  • 2
  • 14

1 Answers1

1

Yes, you have to create new file instead of just copy the path of old file. Since you are using S3 with django-storages, here's how you can do it:

from django.core.files.base import ContentFile
from django.core.files.storage import default_storage


new_file = ContentFile('')
new_file.name = os.path.basename(test_object.some_file.name)
transfer_object.transferred_file = new_file
transfer_object.save()

bucket = default_storage.bucket
original_file = default_storage.open(test_object.some_file.name)
destination_file = default_storage.open(transfer_object.transferred_file.name)
copy_source = {
    'Bucket': bucket.name,
    'Key': original_file.obj.key
}
bucket.copy(copy_source, destination_file.obj.key)
Gasanov
  • 2,839
  • 1
  • 9
  • 21