项目中需要将model的id拼接在图片上,作为图片路径的一部分。实现思路是,动态修改ImageField中的upload_to关键字:
关键代码如下
def custom_upload_path(instance, filename):
class_name= instance.__class__.__name__.lower()
return "{}/{}-{}/{}".format(class_name+"s",class_name, instance.pk, filename)
调用:
class Temple(models.Model):
image = models.ImageField(upload_to=custom_upload_path)#TODO
def __str__(self):
returnself.name
class Monk(models.Model):
image = models.ImageField(upload_to=custom_upload_path)#TODO
def __str__(self):
returnself.name
网友评论