Django,在模型中使用ForeignKey的值
我想做一个系统,照片属于项目。我还启用了可以直接上传项目的 zip 文件,它将解压缩并将照片注册到指定的项目。但是,我在定义 Photo
类时遇到了麻烦。
我需要使用当前实例获取 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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法在同一模型的定义中引用模型中的字段,因为在读取定义时,类尚未定义。
解决方案是使用可调用的
upload_to
- 如图所示 在文档中,这可以是一个给定参数instance
和filename
的函数,因此您可以称呼instance.filepath()
获取正确的路径。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 parametersinstance
andfilename
, so you can callinstance.filepath()
to get the correct path.