copy file from one model to another

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

    Inspired by Gerard's solution I came up with the following code:

    from django.core.files.base import ContentFile
    
    #...
    
    class Example(models.Model):
        file = models.FileField()
    
        def duplicate(self):
            """
            Duplicating this object including copying the file
            """
            new_example = Example()
            new_file = ContentFile(self.file.read())
            new_file.name = self.file.name
            new_example.file = new_file
            new_example.save()
    

    This will actually go as far as renaming the file by adding a "_1" to the filename so that both the original file and this new copy of the file can exist on disk at the same time.

提交回复
热议问题