将文件从一个模型复制到另一个模型 [英] copy file from one model to another

查看:278
本文介绍了将文件从一个模型复制到另一个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个简单的模型:

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

class RealImage(models.Model):
Image = models.ImageField(upload_to =real /)



和一种形式

  class RealImageForm ModelForm):
class Meta:
model = RealImage

文件从UploadImage到RealImage。我怎么可能这样做。
以下代码不起作用

  realform.Image = UploadImage.objects.get(id = image_id).Image 
realform.save()

Tnx寻求帮助。

解决方案

启发Gerard的解决方案我想出了以下代码:

  from django.core.files.base import ContentFile 

#...

类示例(models.Model):
file = models.FileField ()

def duplicate(self):

复制此对象包括复制文件

new_example =
new_file = ContentFile(self.file.read())
new_file.name = self.file.name
new_example.file = new_file
new_example.save()

这实际上会通过向文件名添加一个_1来重命名文件,文件,该文件的新副本可以同时存在磁盘上。


I have 2 simple models:

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

class RealImage(models.Model):
   Image = models.ImageField(upload_to="real/")

And one form

class RealImageForm(ModelForm):
    class Meta:
        model = RealImage 

I need to save file from UploadImage into RealImage. How could i do this. Below code doesn't work

realform.Image=UploadImage.objects.get(id=image_id).Image 
realform.save()

Tnx for help.

解决方案

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.

这篇关于将文件从一个模型复制到另一个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆