2013-04-13 43 views
1

我有一个多语种字段,我使用hvad软件包。 我有一个像下面的脚本,我用于tastypie脱水。根据翻译区分列表

array = [] 
    for t in bundle.obj.facilities.filter(foo_type = i.foo_type): 
     for field in get_translatable_fields(t.foo_type.__class__): 
      for translation in t.foo_type.translations.all(): 
       value = getattr(translation, field) 
       array.append(value) 
       print array 

但我得到所有的语言翻译在同一个列表。你有什么想法让不同的列表属于不同的语言。

我只是想有不同的阵列中for translation in ....迭代

+0

要字典数组,其中的键是语言?另外,为什么你稍后调用'array'然后'array_all'?他们不一样吗? –

+0

是的..键是语言,值是由许多翻译字段组成的数组。 – tunaktunak

+0

这不是原始代码。我改变了字段名称,但忘记了array_all。修复它 – tunaktunak

回答

1

,区分您可以将它们存储在一个字典,由translation索引,使用collections.defaultdict

import collections 

dict_all = collections.defaultdict(list) 
for t in bundle.obj.facilities.filter(foo_type = i.foo_type): 
    for field in get_translatable_fields(t.foo_type.__class__): 
     for translation in t.foo_type.translations.all(): 
      value = getattr(translation, field) 
      dict_all[translation.language_code].append(value) 

如果你想之后将其重新转换为常规字典(而不是defaultdict):

dict_all = dict(dict_all.items()) 
+0

谢谢..解决了这个问题 – tunaktunak