【问题标题】:FileField not respecting upload_to in the context of a South MigrationFileField 在南迁移的情况下不尊重 upload_to
【发布时间】:2014-05-07 16:33:53
【问题描述】:

我最近更改了 FileField 的 upload_to 参数,现在我正在尝试编写 South datamigration 将存储在旧系统下的文件移动到新系统。我写了一些 FileField 文档表明应该可以工作的代码:

def forwards(self, orm):
    for mf in orm.ManagedFile.objects.all():
        print mf.content.path
        oldpath = mf.content.path
        cf = ContentFile(mf.content.read())
        cf.name = oldpath
        mf.content = cf
        mf.save()

这会根据一些默认规则保存所有文件,并且它们最终都会在 MEDIA_ROOT 中松散,而不是在 upload_to 函数指示的位置。

经过一番思考,我明白了为什么会这样,但我能做些什么呢?

【问题讨论】:

  • 在我询问后不久,我在stackoverflow.com/q/6968789/8508 找到了答案。我将把它留在这里,因为对于 FileField 有问题的人来说更容易找到它。 (ImageField 是一个子类)

标签: python django django-south


【解决方案1】:

可以像这样手动重新附加upload_to函数:

 mf._meta.get_field('content').generate_filename = path_maker

生成的代码如下所示:

def path_maker(m_file, filename):
    ext = str(os.path.splitext(filename)[1])
    return os.path.join('m_files', m_file.hash) + ext

...

def forwards(self, orm):
    for mf in orm.ManagedFile.objects.all():
        mf._meta.get_field('content').generate_filename = path_maker
        print mf.content.path
        oldpath = mf.content.path
        cf = ContentFile(mf.content.read())
        cf.name = oldpath
        mf.content = cf
        mf.save()

【讨论】:

    猜你喜欢
    • 2015-08-17
    • 2018-11-08
    • 2015-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 2014-06-22
    • 2021-07-15
    相关资源
    最近更新 更多