首页 > 解决方案 > 为重命名文件创建函数后,Django 无法迁移模型

问题描述

我使用此代码为模型中的重命名文件创建重命名函数。

def path_and_rename(path):
    def path_and_rename_func(instance, filename):
        upload_to = path
        ext = filename.split('.')[-1]
        # get filename
        if instance.pk:
            filename = '{}.{}'.format(instance.pk, ext)
        else:
            # set filename as random string
            filename = '{}.{}'.format(uuid4().hex, ext)
        # return the whole path to the file
        return os.path.join(upload_to, filename)
    return path_and_rename_func

我使用这样的功能。

image=models.ImageField(upload_to=path_and_rename("test_image"))
video=models.FileField(upload_to=path_and_rename("test_file"),blank=True, null=True)

当我使用命令进行迁移时python manage.py makemigrations

它显示这样的错误。

ValueError: Could not find function path_and_rename_func in Test.models.

如何解决?

标签: pythondjangodjango-models

解决方案


您不能使用此类包装函数,因为这意味着生成的函数没有限定名称。

但是,您可以定义两个辅助函数并使用它们,例如:

def path_and_rename_func(instance, filename, path):
    upload_to = path
    ext = filename.split('.')[-1]
    # get filename
    if instance.pk:
        filename = '{}.{}'.format(instance.pk, ext)
    else:
        # set filename as random string
        filename = '{}.{}'.format(uuid4().hex, ext)
    # return the whole path to the file
    return os.path.join(upload_to, filename)

def path_and_rename_test_image(instance, filename):
    return path_and_rename(instance, filename, 'test_image')

def path_and_rename_test_file(instance, filename):
    return path_and_rename(instance, filename, 'test_file')

class MyModel(models.Model):
    image = models.ImageField(upload_to=path_and_rename_test_image)
    video = models.FileField(
        upload_to=path_and_rename_test_file,
        blank=True,
        null=True
    )

推荐阅读