python - 在变量名中使用字典(或其他结构)键

标签 python django

这是一个字典,用于将其键传递给下面的循环。

SIZES = OrderedDict((
    ('image_main', (800, 800)),
    ('thumbsize_big', (200, 200)),
    ('thumbsize_small', (100, 100))))

此代码中的实例是模型实例。传递给字典的键相当于我试图获取值的字段名称。例如,在本例中,字段路径将读取“self.instance.image_main”。 问题是“self.instance.key”(键为字典中的键)似乎不起作用。我尝试了很多方法,例如连接“self.instance”。 + key' 甚至 'self.instance[key]' 但它不起作用。

def execute(self):
    for key, value in self.SIZES.items():
        save_dir = self.base_dir + self.slug + '_' + key
        # Save images in fields. 
        if self.has_iterated == 0:
            # I need self.instance.main_image with main_image dynamically generated form the key
            self.instance.key = self.saving_path + self.slug + '_' + key + '.' + self.image_format 

您是否有其他方法可以实现此功能?目标不是在循环中对字段名称进行硬编码,而是让它从我设置变量的代码上方传递。代码当然得到了简化,但在实际环境中这是为了避免 DRY。

更新:使用 Lambo 实现修改了代码。 循环的第二次迭代似乎引起了问题。

 def execute(self):
    for key, value in self.SIZES.items():
        save_dir = self.base_dir + self.slug + '_' + key
        # Save images on disk. No iteration required: at each iteration, a new file is created and stored.
        self.save_image(self.resize_image(self.image, value),save_dir, self.PNG_COMPRESS, self.JPG_COMPRESS)
        # Save images in fields. Iteration numbered: otherwise field is overwritten at each iteration
        if self.has_iterated == 0:
            setattr(self.instance, key, self.saving_path + self.slug + '_' + key + '.' + self.image_format)
        elif self.has_iterated == 1:
            setattr(self.instance, key, self.saving_path + self.slug + '_' + key + '.' + self.image_format)
        else:
            setattr(self.instance, key, self.saving_path + self.slug + '_' + key + '.' + self.image_format)
        self.has_iterated += 1

    return self.instance

最佳答案

您想要使用setattr()setattr(x, 'y', z) 相当于 x.y = z (请注意,第二个参数是一个字符串 - 在您的情况下,它将是 >key 字符串)。因此,就您而言,您可以这样做:

setattr(self.instance, key, self.saving_path + self.slug + '_' + key + '.' + self.image_format)

关于python - 在变量名中使用字典(或其他结构)键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34922038/

相关文章:

python - Django 查看相同 url 模式请求的执行顺序?

python - 如何在 ubuntu 10.04 中为 django 框架安装 libmemcached

django - 修复表单 View 以隐藏 django 中经过身份验证的用户字段

python - Django:请求的资源上不存在 'Access-Control-Allow-Origin' header

来自 R 的 do.call(rbind, lapply()) 的 Python 等价物

javascript - 使用 angularjs 或 javascript 的 flask reSTLess 批量删除,这可能吗?

python - 在 Python 中为线性拟合(具有两个参数)生成置信区间等高线图

python - 将 json 转换为 pandas DataFrame

django - 在DRF中拒绝权限时返回自定义消息

python - 无法从类中抓取文本 (BeautifulSoup)