Django,在模型中使用ForeignKey的值 [英] Django, use of ForeignKey's value within model
问题描述
照片
类时,我遇到麻烦。 我需要获取 Project.file_zip.path
的值与当前实例定义 img
字段的 upload_to
属性。但是,当我尝试如下,它返回与 AttributeError:'ForeignKey'对象没有属性'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))
类照片(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)
您不能在同一模型的定义中引用模型中的字段,就像定义读取类hasn时一样没有定义。
解决方案是使用可调用 upload_to
- 如下所示在文档中,这可以是给出参数实例的一个函数
和 filename
,所以你可以调用 instance.filepath()
来获取正确的路径。
I would like to make a system, which is photos belong to projects. I also enabled that I can upload a zipfile directly for a project and it will unzip and register the photos to the specified project. However, I am having troubles while defining the Photo
class.
I need to get the value of Project.file_zip.path
with the current instance for defining img
field's upload_to
attribute. However, when I tried like below, it returns with AttributeError: 'ForeignKey' object has no attribute 'file_path'
. How do I fix that?
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)
You can't refer to fields in a model within that same model's definition, as at the point when the definition is being read the class hasn't been defined yet.
The solution is to use a callable for upload_to
- as shown in the documentation, this can be a function that is given the parameters instance
and filename
, so you can call instance.filepath()
to get the correct path.
这篇关于Django,在模型中使用ForeignKey的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!