Django 1.8通过FileField上的动态upload_to进行迁移失败

时间:2015-06-03 15:22:38

标签: python django django-models django-migrations

尝试在具有动态upload_to路径的FileField的模型上使用迁移时,我遇到以下错误。

    field=models.FileField(null=True, upload_to=core.models.UserProfile.upload_path, blank=True),
AttributeError: type object 'UserProfile' has no attribute 'upload_path'

我的代码:

def upload_path(instance, filename):
    return os.path.join(str(instance.user.id),filename)

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='userprofile')
    document_upload = models.FileField(upload_to=upload_path,null=True, blank=True)

1 个答案:

答案 0 :(得分:0)

您可以使用@deconstructor类装饰器,这允许装饰类由迁移子系统序列化

实施例

from django.utils.deconstruct import deconstructible

@deconstructible
class UploadPath(object):

    def __call__(self, instance, filename):
        return os.path.join(str(instance.user.id),filename)

upload_path= UploadPath()

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='userprofile')
    document_upload = models.FileField(upload_to=upload_path, null=True, blank=True)

了解更多: