有一个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
同时它好像还说必须要两个参数:instance
和filename
。
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下面岂不是不兼容?