小编典典

将Django的FileField设置为现有文件

django

我在磁盘上有一个现有文件(例如/folder/file.txt),在Django中有一个FileField模型字段。

当我做

instance.field = File(file('/folder/file.txt'))
instance.save()

它将文件另存为file_1.txt(下次是_2,等等)。

我知道为什么,但是我不想要这种行为-我知道我想要与该字段关联的文件确实在那里等着我,我只想让Django指向它。


阅读 899

收藏
2020-04-02

共2个答案

小编典典

如果要永久执行此操作,则需要创建自己的FileStorage类

import os
from django.conf import settings
from django.core.files.storage import FileSystemStorage

class MyFileStorage(FileSystemStorage):

    # This method is actually defined in Storage
    def get_available_name(self, name):
        if self.exists(name):
            os.remove(os.path.join(settings.MEDIA_ROOT, name))
        return name # simply returns the name passed

现在在模型中,使用修改后的MyFileStorage

from mystuff.customs import MyFileStorage

mfs = MyFileStorage()

class SomeModel(model.Model):
   my_file = model.FileField(storage=mfs)
2020-04-02
小编典典

只需设置instance.field.name为文件的路径

例如

class Document(models.Model):
    file = FileField(upload_to=get_document_path)
    description = CharField(max_length=100)


doc = Document()
doc.file.name = 'path/to/file'  # must be relative to MEDIA_ROOT
doc.file
<FieldFile: path/to/file>
2020-04-02