2011-08-09 88 views
0

我想制作一个系统,它是属于项目的照片。我还启用了可以直接上传项目的zip文件,并将其解压并将照片注册到指定的项目。但是,我在定义Photo类时遇到了麻烦。Django,在模型中使用ForeignKey的值

我需要获取Project.file_zip.path的值与当前实例定义img字段的upload_to属性。但是,当我尝试如下时,它会返回AttributeError: 'ForeignKey' object has no attribute 'file_path'。我如何解决这个问题?

class Project(models.Model): 
.... 
owner=models.ForeignKey(User) 
file_zip=models.FileField(upload_to='projects/%Y/%m/%d') 

def __unicode__(self): 
    return self.project_name 

def file_path(self): 
    return re.search(re.search('[^\s]+(?=\.zip)', self.file_zip).group(0)) 

class Photo(models.Model): 
    belongs_to=models.ForeignKey(Project) 
    img=models.ImageField(upload_to='/home/contact/python_project/all_bugs_will_reveal/'+belongs_to.file_path()) 
    desc=models.CharField(max_length=255) 

回答

3

你不能指领域模型中的同一型号的定义中,作为当定义被读取时类别的点还没有确定。

的解决方案是使用一个可调用的upload_to - 如图所示in the documentation,这可以是给出的参数instancefilename功能,这样你就可以调用instance.filepath()得到正确的路径。

+0

我想你按照你的指示,但;要么我定义了无效的函数,要么我没有以正确的方式调用它。 'def project_path(instance,filename): return'%s /%s'%(instance.belongs_to.file_path,filename)'和'img = models.ImageField(upload_to = project_path())'返回TypeError:project_path ()只需要2个参数(0给出)' –

+0

应该是'ImageField(upload_to = project_path)' - 没有调用括号。否则,在定义表单时不调用参数,而不是上传文件时调用该函数。 –

+0

是的,我实际上写了正确的代码,但在其他地方犯了一个错误,并且在试图找到该错误时,我也改变了它。现在运作良好。谢谢。 –

相关问题