【问题标题】:Django: How do I insert an existing file into the db?Django:如何将现有文件插入数据库?
【发布时间】:2009-12-18 21:43:10
【问题描述】:

用户上传了一个文件,我将该文件转换为新格式。如何将创建的文件插入数据库?

当我执行明显的 field.file = newfile 时,它​​会尝试上传它。所以,我想问题是,如何在不尝试将文件写入文件系统的情况下将文件添加到数据库?

--编辑-- 我不想将文件存储在数据库中。我只想设置 FileField 指向的路径,而不让 FileField 尝试将文件写入磁盘(因为它已经在磁盘上)。

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    您当然仍然可以通过直接修改数据库来执行此操作(就像我刚才所做的那样)。您可以使用基于 django 的脚本创建要执行的 sql 代码,然后通过您的数据库运行它(在我的例子中是 sqlite3):

    # Set up django environment
    from django.core.management import setup_environ
    from app import settings
    setup_environ(settings)
    
    from project.app.models import MyModel
    
    # Prints sql to update file locations since django won't :(
    
    for myModel in MyModel.objects.all():
      # You can do the below even better if you use the same method as the model uses
      # to generate upload_to
      file_name = 'my_file_this_should_depend_on_myModel'
      file_location = 'path/to/file/dir/%s' % file_name
      print "UPDATE app_mymodel SET file_field='%s' WHERE id=%s;" % \
        (file_location, myModel.id)
    

    然后使用此脚本的输出并通过您的数据库运行它!

    【讨论】:

      【解决方案2】:

      简短的回答,在 Django 中没有直接的方法可以做到这一点,核心开发人员并不热衷于此 - 请参阅票 #652

      【讨论】:

      • 票证与问题无关 - 票证是将文件上传到数据库内的 blob,而问题是更改文件字段以指向文件系统上的现有文件而不是上传...
      【解决方案3】:

      Set Django's FileField to an existing file 是一个较新的副本,但那里的答案似乎比直接修改数据库更好。

      【讨论】:

        猜你喜欢
        • 2016-06-06
        • 2014-12-06
        • 1970-01-01
        • 2014-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-15
        相关资源
        最近更新 更多