6
我從數據庫中讀取這些行:結合幾個對象的值到一個單一的字典
blog_id='12', field_name='title', translation='title12 in en', lang='en'
blog_id='12', field_name='desc', translation='desc12 in en', lang='en'
blog_id='13', field_name='title', translation='title13 in en', lang='en'
blog_id='13', field_name='desc', translation='desc13 in en', lang='en'
....
,我想建立一個單一的字典每個blog_id:例如
[
{'blog': '12', 'title': 'title12 in en', 'desc': 'desc12 in en'},
{'blog': '13', 'title': 'title13 in en', 'desc': 'desc13 in en'},
....
]
我想是這樣的:
res = []
dict_ = {}
for trans in translations: # 'translations' is QuerySet, already filtered by 'en'
if trans.blog_id in dict_.values():
dict_[trans.field_name] = trans.translation
else:
dict_['blog'] = trans.blog_id
dict_[trans.field_name] = trans.translation
res.append(dict_)
但這是錯誤洙,res
這裏包含blog 13
3次,blog 12
甚至在最終名單狀態並沒有。我現在覺得很愚蠢,我錯過了什麼?
您添加相同的字典對象'res',你甚至沒有創建新的字典對象 – thefourtheye
@thefourtheye我知道:(我需要創建新的字典動態莫名其妙... – doniyor
爲什麼不使用'blog_id'作爲外鍵,並創建一個字典類型的字典? –