Python 如何使用attr string name在Django模型类中调用save()方法?

Python 如何使用attr string name在Django模型类中调用save()方法?,python,django,Python,Django,例如,在我的代码中: class ClassName(): [...] image_bigger = models.ImageField(upload_to='dir', max_length=500, blank=True, null=True) image_big = models.ImageField(upload_to='dir', max_length=500, blank=True, null=True) image_medium = models.I

例如,在我的代码中:

class ClassName():
    [...]
    image_bigger = models.ImageField(upload_to='dir', max_length=500, blank=True, null=True)
    image_big = models.ImageField(upload_to='dir', max_length=500, blank=True, null=True)
    image_medium = models.ImageField(upload_to='dir', max_length=500, blank=True, null=True)
    image_small = models.ImageField(upload_to='dir', max_length=500, blank=True, null=True)

    def create_resized(self, attr_name, resized_size):
        [...]

        if attr_name == "bigger":
            self.bigger.save(filename, suf, save=False)
        elif attr_name == "big":
            self.big.save(filename, suf, save=False)
        elif attr_name == "medium":
            self.medium.save(filename, suf, save=False)
        elif attr_name == "small":
            self.small.save(filename, suf, save=False)

我想知道是否有类似getattr的东西可以避免丑陋的if-elif代码块…

为什么不使用getattr/hasattr调用?你可以这样写:

full_attr_name = 'image_' + attr_name
if hasattr(self, full_attr_name):
    getattr(self, full_attr_name).save(filename, suf, save=False)

希望,你已经抓住了这个想法。

如果你有不同大小的图像,那么我认为使用sorl缩略图会是一个更好的方法。链接已附加


如果
attr\u name==“small”
你真的想保存
self.medium
?好的,奈杰尔·塔夫内尔,那是个bug。编辑!没有。。。save()方法在哪里?很抱歉丢失了;相信getattr(self,full\u attr\u name)。save(filename,suf,save=False)应该适合您