尝试在具有动态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)
答案 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)
了解更多: