Django, use of ForeignKey's value within model

2019-09-02 14:35发布

问题:

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)

回答1:

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.