我尝试将实例的多个图像上传到不同的子文件夹。但我需要重命名每个上传的文件,所以我实现了upload_to字段的功能,如下所示。
class MyModel(models.Model):
code = models.CharField()
logo = models.FileField(upload_to=get_path)
cover = models.FileField(upload_to=get_path)
def get_path(instance, filename):
ext = filename.split('.')[-1]
new_name = "%s.%s" % (slughifi(filename), ext)
return new_name
但是,我不确定如何将图片划分为logos
和cover_images
等子文件夹
如果我将参数传递给get_path函数(例如
...
logo = models.FileField(upload_to=get_path("logos/"))
cover = models.FileField(upload_to=get_path("cover_images/"))
...
我是否需要为每个文件字段编写不同的upload_to函数?
答案 0 :(得分:0)
我认为不,
你可以这样使用它:
upload_to=lambda s,f: MyModel.upload_to(s,f,your_custom_path)
@classmethod
def upload_to(cls, obj, filename, custom_path):
name,extension = os.path.splitext(filename)
new_name = "%s.%s" % (slughifi(filename), extension)
return "{}{}".format(custom_path, new_name)