django,试图操纵queryset并返回模板

时间:2012-10-24 18:16:51

标签: django django-views

我正在尝试对模型的单个字段中的所有元素执行操作,但是我收到错误:

list indices must be integers, not tuple

这是views.py中的索引函数:

design_list = Design.objects.values_list().order_by('-date_submitted')[:10]

x=list(design_list)
for i in x:
    b = list(x[i]) # ERROR RELATES TO THIS LINE
    c = b[2]
    b[2] = datetimeConvertToHumanReadable(c) 
    new_list[i] = b

return render_to_response('index.html', {
    'design_list': new_list,    
})

我确定这是一个常见的问题,有谁知道我做错了什么?

2 个答案:

答案 0 :(得分:2)

Python不是C - for x in y循环不会循环索引,而是覆盖项目本身。

design_listlist of tuples,因此您可以将其视为此类。元组是不可变的,因此您需要创建一个新列表。列表理解可能是最好的。

# Create a new list of tuples
new_list = [row[:2] + (datetimeConvertToHumanReadable(row[2]),) + row[3:]
            for row in x]

然而,您似乎并不真的需要使用元组,因为您对错误感到困惑。如果是这种情况,那么不要使用values_list(返回元组),而只是使用order_by,并直接引用该字段(我假设它被称为date_submitted)。

design_list = Design.objects.order_by('-date_submitted')[:10]

x=list(design_list)
for row in x:
    row.date_submitted = datetimeConvertToHumanReadable(row.date_submitted) 

return render_to_response('index.html', {
    'design_list': x,
})

答案 1 :(得分:1)

for i in x:遍历x,而不是索引。如果不分析代码背后的意图(以及QuerySets的正确使用),可以将该行更改为:

b = list(i)

以避免此特定错误。