Django,在模型中使用ForeignKey的值 [英] Django, use of ForeignKey's value within model

查看:411
本文介绍了Django,在模型中使用ForeignKey的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我需要获取 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆