[Django]如何对models.FileField()动态生成上传路径?

有一个Model类似这样:

class Report(models.Model):
    path = models.FileField(upload_to='uploads/')

需要根据Model具体的使用场景动态的生成路径,比如:date/type/report_name

我看到官网给了一个例子:

def user_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    return 'user_{0}/{1}'.format(instance.user.id, filename)

class MyModel(models.Model):
    upload = models.FileField(upload_to=user_directory_path)

from: 1.11 django.db.models.FileField.upload_to

同时它好像还说必须要两个参数:instancefilename

This callable must accept two arguments

这让我很头疼啊,我不光需要这两个参数啊。

另外,我看到它说这个instance实际上就是这个Model的实例,那就是self喽?
也许我可以这样,把我想要用的参数传递给这个Model,然后通过instance访问,如下:

class Report(models.Model):
    path = models.FileField(upload_to=report_path)
    
    def __init__(self, date, type):
        super(self.__class__, self).__init__()
        self.date = date
        self.type = type
    
    def __str__(self):
        pass
    
    def report_path(self, filename):
        return '{}/{}/{}'.format(self.date, self.type, filename)

但是这样也太麻烦了吧?还是我理解有误?

另外,report_path那个地方返回的路径文档说用

a Unix-style path

os.path.join()不是更好么,不然win下面岂不是不兼容?

阅读 5.5k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题