0

I have this function below and I need to also check if each of these variables are none before translating.

def save(self):
    # add an an if condition to check all the below variables if they are none
    # if self.name_es or ..... is not None:
    self.name_es = translateField(self.name, 'es') if not None
    self.name_ar = translateField(self.name, 'ar')
    self.description_es = translateField(self.description, 'es')
    self.description_ar = translateField(self.description, 'ar')
    super(City, self).save()

This is the translate function:

def translateField(text, lang):
    try:
        return client.translate(text, lang)
    except:
        pass

The problem is that I have the above in like many classes in my Model. In each save function I'm doing the same for different variables.

What can I do over here to minimize the amount of code? The '_es' and '_ar' are always appended to these variables that I need to return the output of the translation.

4

1 回答 1

1

使用setattr

for lang in ["es", "ar"]:
    setattr(self, "name_" + lang, translateField(self.name, lang))
    setattr(self, "description_" + lang, translateField(self.description, 'es'))

如果您有很多字段以及多种语言,那么您甚至可以将其设为嵌套循环。

我可以警告不要使用裸except条款吗?

于 2013-09-06T14:31:08.630 回答