copy file from one model to another

后端 未结 5 1706
孤城傲影
孤城傲影 2020-12-09 03:34

I have 2 simple models:

class UploadImage(models.Model):
   Image = models.ImageField(upload_to=\"temp/\")

class RealImage(models.Model):
   Image = models.         


        
5条回答
  •  囚心锁ツ
    2020-12-09 04:09

    I had the same problem and solved it like this, hope it helps anybody:

    # models.py
    class A(models.Model):
        # other fields...
        attachment = FileField(upload_to='a')
    
    class B(models.Model):
        # other fields...
        attachment = FileField(upload_to='b')
    
    # views.py or any file you need the code in
    try:
        from cStringIO import StringIO
    except ImportError:
        from StringIO import StringIO
    from django.core.files.base import ContentFile
    from main.models import A, B
    
    obj1 = A.objects.get(pk=1)
    
    # You and either copy the file to an existent object
    obj2 = B.objects.get(pk=2)
    
    # or create a new instance
    obj2 = B(**some_params)
    
    tmp_file = StringIO(obj1.attachment.read())
    tmp_file = ContentFile(tmp_file.getvalue())
    url = obj1.attachment.url.split('.')
    ext = url.pop(-1)
    name = url.pop(-1).split('/')[-1]  # I have my files in a remote Storage, you can omit the split if it doesn't help you
    tmp_file.name = '.'.join([name, ext])
    obj2.attachment = tmp_file
    
    # Remember to save you instance
    obj2.save()
    

提交回复
热议问题