为 Django 1.7 重构调用
Refactoring callable for Django 1.7
我正在从 Django 1.6 升级到 1.7,我遇到了一个棘手的问题。我有一个像这样的个人资料图片的模型字段:
profile_image = models.ImageField(
upload_to=get_user_uploadto_callable('photos'), null=True,
verbose_name=_('photo'), blank=True)
...我的 get_user_uploadto_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
参数。是否有一个干净的方式来做到这一点?
不可能使用 get_user_uploadto_callable
的结果作为 Python 2 中的可调用函数,但您可以定义一个函数来做同样的事情。
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)
我正在从 Django 1.6 升级到 1.7,我遇到了一个棘手的问题。我有一个像这样的个人资料图片的模型字段:
profile_image = models.ImageField(
upload_to=get_user_uploadto_callable('photos'), null=True,
verbose_name=_('photo'), blank=True)
...我的 get_user_uploadto_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
参数。是否有一个干净的方式来做到这一点?
不可能使用 get_user_uploadto_callable
的结果作为 Python 2 中的可调用函数,但您可以定义一个函数来做同样的事情。
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)