Skip to main content
 首页 » 编程设计

python之Django 根据外键将文件保存在动态路径下

2024年12月31日26think

我有这些模型:

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 将文件上传到文件夹。我该怎么做?

请您参考如下方法:

这应该可以满足您的需求:

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 .