Upload_to包含对象名称

时间:2017-12-07 04:56:32

标签: django django-models

我有一个问题,我认为你们在Django上对upload_to很容易,但这对我来说很难。希望你的帮助!

# Upload_to Def
from datetime import datetime
def avatar_country_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = '%s' % (instance.id)
    datetime_str = datetime.now().strftime("%Y%m%d%H%M%S")
    return "geo/country/%s/%s_avatar.%s" %(filename, datetime_str, ext)

def cover_country_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = '%s' % (instance.id)
    datetime_str = datetime.now().strftime("%Y%m%d%H%M%S")
    return "geo/country/%s/%s_cover.%s" %(filename, datetime_str, ext)

def flag_country_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = '%s' % (instance.id)
    datetime_str = datetime.now().strftime("%Y%m%d%H%M%S")
    return "geo/country/%s/%s_flag.%s" %(filename, datetime_str, ext)

class BaseCountry(Place, SlugModel):
    # More
    avatar = models.ImageField(max_length=1024, upload_to=avatar_country_path, blank=True)
    cover = models.ImageField(max_length=1024, upload_to=cover_country_path, blank=True)
    flag = models.ImageField(max_length=1024, upload_to=flag_country_path, blank=True

如您所见,我需要3个函数来使upload_to具有相似的Path,在NAME OF FIELDS (avatar, cover, flag)中只是不同但我不知道如何缩短它。

你们能帮助我吗?

1 个答案:

答案 0 :(得分:3)

弄清楚如何缩短这样的代码的一个技巧是寻找重复的行,然后尝试参数化其余部分:

from datetime import datetime

def inject_field_type(instance, filename, suffix):
    ext = filename.split('.')[-1]
    filename = '%s' % (instance.id)
    datetime_str = datetime.now().strftime("%Y%m%d%H%M%S")
    return "geo/country/%s/%s_%s.%s" %(filename, datetime_str, ext, suffix)

def avatar_country_path(instance, filename):
    return inject_field_type(instance, filename, 'avatar')

def cover_country_path(instance, filename):
    return inject_field_type(instance, filename, 'cover')

def flag_country_path(instance, filename):
    return inject_field_type(instance, filename, 'flag')

class BaseCountry(Place, SlugModel):
    avatar = models.ImageField(max_length=1024, upload_to=avatar_country_path, blank=True)
    cover = models.ImageField(max_length=1024, upload_to=cover_country_path, blank=True)
    flag = models.ImageField(max_length=1024, upload_to=flag_country_path, blank=True

通过这种方式,您可以更改创建路径所需的逻辑,影响所有3个字段,而不必在3个不同的函数中更改它。