I’m trying to perform an operation on all the elements from a single field of a model, but I’m getting an error:
list indices must be integers, not tuple
Here’s my index function in 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,
})
I’m sure this is a common problem, does anyone know what I’m doing wrong?
Python is not C – the
for x in yloop does not loop over indices, but over the items themselves.design_listis a list of tuples, so you can treat it as such. Tuples are immutable, therefore you’ll need to create a new list. A list comprehension would probably be best.However, it doesn’t seem like you really need to use tuples, since you were confused by the error. If this is the case, then don’t use
values_list(which returns tuples), but just useorder_by, and reference the field directly (I’ll assume it’s calleddate_submitted).