Django:复制FileFields

Joe*_*e J 4 django copy file path hardlink

我正在尝试使用硬链接复制文件,其中文件存储为Django FileField.我想使用硬链接来节省空间和复制时间(预计不会对原始文​​件或副本进行任何更改).但是,当我尝试从下面的代码段调用new_file.save()时,我遇到了一些奇怪的错误.

AttributeError: 'file' object has no attribute '_committed'
Run Code Online (Sandbox Code Playgroud)

我的想法是,在制作硬链接后,我可以打开链接文件并将其存储到Django新的File实例的FileFile中.我错过了这里的一步还是什么?

models.py

class File(models.Model):
    stored_file = models.FileField()
Run Code Online (Sandbox Code Playgroud)

elsewhere.py

import os 

original_file = File.objects.get(id=1)
original_file_path = original_file.file.path

new_file = File()
new_file_path = '/path/to/new/file'

os.makedirs(os.path.realpath(os.path.dirname(new_file_path)))
os.link(original_file_path, new_file_path)
new_file.stored_file = file(new_file_path)
new_file.save()
Run Code Online (Sandbox Code Playgroud)

okm*_*okm 8

无需创建硬链接,只需复制文件夹:

new_file = File(stored_file=original_file.stored_file)
new_file.save()
Run Code Online (Sandbox Code Playgroud)

更新

如果要将文件指定到FileField或ImageField,您可以简单地

new_file = File(stored_file=new_file_path)
# or
new_file = File()
new_file.stored_file = new_file_path
# or
from django.core.files.base import File
# from django.core.files.images import ImageFile # for ImageField
new_file.stored_file = File(new_file_path)
Run Code Online (Sandbox Code Playgroud)

该字段接受basestring或File()实例中的路径,您的问题中的代码使用file(),因此不被接受.