Django1.7可调用的重构

2024-05-16 17:48:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从django1.6升级到1.7,遇到了一个棘手的问题。我有一个模型字段用于如下配置文件图片:

profile_image = models.ImageField(
    upload_to=get_user_uploadto_callable('photos'), null=True,
    verbose_name=_('photo'), blank=True)

…我的get\u user\u uploadto\u callable如下所示:

def get_user_uploadto_callable(subdir):
    '''Return a callable that returns a custom filepath/filename
    for an uploaded file as per `get_user_upload_path`.

    '''

    def _callable(instance, filename):
        return get_user_upload_path(instance, subdir, filename)

    return _callable

但是,Django不再接受这种情况,在尝试进行迁移时会导致此错误:

ValueError: Could not find function _callable in myproj.core.util.
Please note that due to Python 2 limitations, you cannot serialize unbound method functions (e.g. a method declared
and used in the same class body). Please move the function into the main module body to use migrations.
For more information, see https://docs.djangoproject.com/en/1.7/topics/migrations/#serializing-values

因此,我需要将这个_callable移到方法之外(可能将其重命名为user_uploadto_callable之类的名称),但仍然可以访问传入的subdir参数。有没有干净的方法


Tags: thetopathinstancetruegetreturnthat
1条回答
网友
1楼 · 发布于 2024-05-16 17:48:02

在python2中不可能使用get_user_uploadto_callable的结果作为可调用的,但是可以定义一个函数来执行相同的操作

def profile_image_upload_to():
    # you can reduce this to one line if you prefer, I used
    # two to make it clearer how it works
    callable = get_user_uploadto_callable('photos')
    return callable()

class MyModel(models.Model):
    profile_image = models.ImageField(
        upload_to=profile_image_upload_to, null=True,
        verbose_name=_('photo'), blank=True)

相关问题 更多 >