将Django的FileField设置为现有文件 [英] Set Django's FileField to an existing file

查看:869
本文介绍了将Django的FileField设置为现有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



当我执行

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

它将文件重新保存为 file_1.txt (下一次它是 _2 等)。



我明白为什么,但我不想要这个行为 - 我知道我想要的字段与之相关联的文件真的在等我,而我只想让Django指向它。



如何?

解决方案

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

  from django.core.files.storage import FileSystemStorage 

class MyFileStorage(FileSystemStorage):

#此方法实际上定义在存储
def get_available_name(self,name):
返回名称#只需返回名称ed

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

 从mystuff.customs导入MyFileStorage 

mfs = MyFileStorage()

class SomeModel(model.Model):
my_file = model.FileField(storage = mfs)


I have an existing file on disk (say /folder/file.txt) and a FileField model field in Django.

When I do

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

it re-saves the file as file_1.txt (the next time it's _2, etc.).

I understand why, but I don't want this behavior - I know the file I want the field to be associated with is really there waiting for me, and I just want Django to point to it.

How?

解决方案

If you want to do this permanently, you need to create your own FileStorage class

from django.core.files.storage import FileSystemStorage

class MyFileStorage(FileSystemStorage):

    # This method is actually defined in Storage
    def get_available_name(self, name):
      return name # simply returns the name passed

Now in your model, you use your modified MyFileStorage

from mystuff.customs import MyFileStorage

mfs = MyFileStorage()

class SomeModel(model.Model):
   my_file = model.FileField(storage=mfs)

这篇关于将Django的FileField设置为现有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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