python - 根据翻译区分列表

标签 python django list multilingual

我有一个多语言字段,我使用了 hvad 包。 我有一个如下所示的脚本,用于美味馅饼脱水。

    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

但我在同一个列表中得到了所有语言翻译。您是否知道让不同的列表属于不同的语言。

我只是想让不同的数组在翻译过程中区分......迭代

最佳答案

您可以使用 collections.defaultdict 将它们存储在字典中,由 translation 索引:

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())

关于python - 根据翻译区分列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15992225/

相关文章:

python - Django : 'WSGIRequest' object has no attribute 'user' ? - AuthenticationMiddleware & SessionAuthenticationMiddleware 顺序

c# - WPF 绑定(bind) : How to bind a name from a list of filepaths to text of TextBlock in ListBox?

Python pygame 角色闲置动画

python - 将数据库添加到 Mezzanine 项目会产生 "sqlite3.OperationalError: no such table: django_site"

python - Django: 'WSGIRequest' 对象没有属性 'PUT'

python - 如何在 Django 中增加 IntegerField?

list - 将数字列表拆分为对列表列表

python - 在 Python 中根据属性对对象列表进行排序的更快方法

python - 使用 Python 2.7 读写 CSV 文件,包括 unicode

python - python - 如何在python字符串中始终将负零格式化为正零?