2016-01-21 62 views
1

这是一个用于将键传递给下面循环的词典。在变量名中使用字典(或其他结构)键

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

此代码中的实例是模型实例。传递给字典的密钥等价于我试图获取值的字段名称。例如,在这种情况下,字段路径会读取'self.instance.image_main'。 问题是'self.instance.key'与键是来自字典的键似乎不起作用。我尝试了很多东西,比如连接'self.instance。 +键'甚至是'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 
+0

究竟什么不起作用? self.instance [key]就是你需要的。 –

+0

这是我所期望的,但会产生:'文档'对象不支持项目分配。文件是我的模型。 –

回答

2

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

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

谢谢,这很有道理。我在循环中运行了其中的几个,看起来第一个运行正常,但不是后来的运行。我是否需要在每次迭代时使用它来“清除”某些内容? –

+0

很难知道,而无法看到更多的代码。上述解决方案应该始终工作,只要你传递一个有效的对象,字符串和值给'setattr'函数..... – gtlambert

+0

完整的代码张贴在帖子更新。 –

相关问题