copy file from one model to another

后端 未结 5 1728
孤城傲影
孤城傲影 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:04

    Update Gerard's Solution to handle it in a generic way:

    try:
        from cStringIO import StringIO
    except ImportError:
        from StringIO import StringIO
    
    from django.core.files.base import ContentFile
    
    init_str = "src_obj." + src_field_name + ".read()"
    file_name_str = "src_obj." + src_field_name + ".name"
    
    try:
        tmp_file = StringIO(eval(str(init_str)))
        tmp_file = ContentFile(tmp_file.getvalue())
        tmp_file.name = os.path.basename(eval(file_name_str))
    except AttributeError:
        tmp_file = None
    
    if tmp_file:
        try:
            dest_obj.__dict__[dest_field_name] = tmp_file
            dest_obj.save()
        except KeyError:
            pass
    

    Variable's Used:

    1. src_obj = source attachment object.
    2. src_field_name = source attachment object's FileField Name.
    3. dest_obj = destination attachment object.
    4. dest_field_name = destination attachment object's FileField Name.

提交回复
热议问题