【发布时间】:2018-01-08 23:27:18
【问题描述】:
如果标题有点难以理解,请道歉。 不太清楚如何在一行内解释它。
我想做的是……
其实我有这个代码
output = []
objs = Model.objects.filter(abc=abc) # this would return a some queryset
for obj in objs:
output.append({
TITLE: obj.title,
TYPE: obj.type,
# I want to add something here which is kind of like, if `obj.type` is 'hello' then print obj.word
})
return output
例如,如果我的obj.type 是“你好”
我想要
output.append({
TITLE: obj.title,
TYPE: obj.type,
WORD: obj.word,
})
如果我的obj.type 是“世界”
我想要
output.append({
TITLE: obj.title,
TYPE: obj.type,
NADA: obj.nada,
})
我想过做一些事情,比如
output = []
objs = Model.objects.filter(abc=abc) # this would return a some queryset
for obj in objs:
if obj.type == 'hello':
output.append({
TITLE: obj.title,
TYPE: obj.type,
WORD: obj.word,
})
if obj.type == 'world':
output.append({
TITLE: obj.title,
TYPE: obj.type,
NADA: obj.nada,
})
return output
上面应该可以工作,但是如果有另一种更好的方法,我很想知道另一种方法,因为上面看起来太多余了。
提前感谢您的任何建议
【问题讨论】:
标签: python django list dictionary append