使用Django 1.7迁移的Python 2.7未绑定方法

Chr*_*ris 4 python django django-models django-south python-2.7

我正在升级到Django 1.7.4并使用新的内置迁移,但在尝试运行时出现以下错误makemigrations:

ValueError: Could not find function upload_callback in app_utils.
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
Run Code Online (Sandbox Code Playgroud)

我的模型定义:

class Discount(models.Model):
    banner = models.ImageField(
        help_text=_("Banner image for this discount"),
        upload_to=upload_to('discounts/', 'title'),
        blank=True,
        null=True
    )
Run Code Online (Sandbox Code Playgroud)

我的上传回调app_utils.py:

def upload_to(path, attribute=None):
    def upload_callback(instance, filename):
        compact = filename[:50]
        try:
            attr= unicode( slugify( getattr(instance, attribute) ) )
            mypath = '%s/%s/%s' % (path, attr, compact)
        except:
            mypath = '%s%s' % (path, compact)
        return mypath
    return upload_callback
Run Code Online (Sandbox Code Playgroud)

根据错误消息,它表示upload_callback未绑定.所以我试着upload_callback在包装函数之外拉,但是找不到传递额外pathattribute传入参数的方法upload_to.Django的文档不清楚如何做到这一点,它只指定instance并且filename是必需的.

理想情况下,我想要的是:

def upload_to(instance, filename, path, attribute=None):
    ...
Run Code Online (Sandbox Code Playgroud)

我有什么想法可以实现这个目标吗?

Chr*_*ris 7

经过对网络的深入挖掘,我发现了这个Django错误报告.该解决方案似乎创建了一个可调用的工厂类:

https://code.djangoproject.com/ticket/22999

这里有更多讨论:Django - 无法使用动态upload_to值为ImageField创建迁移