Django根据ForeignKey在动态路径下保存文件

时间:2018-10-02 08:54:46

标签: python django

我有以下模型:

class Project():
    name = models.CharField(max_length=512)

class Task():
    name = models.CharField(max_length=256)
    project = models.ForeignKey('prosystem.Project',
                                related_name='tasks',
                                on_delete=models.CASCADE)

class TaskFile(models.Model):
    task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='tasks')
    file = models.FileField(upload_to=self.make_file_path())        # I want this to be dynamic path

    def make_file_path(self):
       # pseudocode, does not work
       pid = self.task.project.id
       tid = self.task.id
       path = f'project_{pid}/task_{tid}/'
       return path

我想基于其Task ID和其父Project ID将文件上传到文件夹。我该怎么办?

2 个答案:

答案 0 :(得分:1)

这应该可以满足您的需求

class Project():
    name = models.CharField(max_length=512)

class Task():
    name = models.CharField(max_length=256)
    project = models.ForeignKey('prosystem.Project',
                                related_name='tasks',
                                on_delete=models.CASCADE)

def make_file_path(instance, filename):

   pid = instance.task.project.id
   tid = instance.task.id
   path = f'project_{pid}/task_{tid}/{filename}'

   return path

class TaskFile(models.Model):
    task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='tasks')

    # Please note that "()" have been removed here. You don't want to
    # give the result of make_file_path() but the function itself
    file = models.FileField(upload_to=make_file_path)

有关更多信息,请参阅documentation about FileField.upload_to

答案 1 :(得分:0)

You need to create a CustomFileStorage and add it to your file field. Info here