在以下代码中,“ row [header]”出现错误:
for field in Document._meta.get_fields():
headers.append(field.name)
docs = Document.objects.order_by('id')
for doc in docs:
row = {}
for header in headers:
if hasattr(doc, header):
row[header] = getattr(doc, header)
files.append(row)
Python说:TypeError:列表索引必须是整数或切片,而不是str
出了什么问题?
Python追溯:
Traceback (most recent call last):
File "/home/niels/PycharmProjects/sitesv/env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/niels/PycharmProjects/sitesv/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/niels/PycharmProjects/sitesv/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/niels/PycharmProjects/sitesv/files/views.py", line 87, in get_file_list
row[header] = getattr(doc, header)
TypeError: list indices must be integers or slices, not str
答案 0 :(得分:0)
从评论中确认答案:
变量row
已经在更高的范围内,因此对它的写入将被另一个线程对其的写入所覆盖。
将row
的名称更改为其他名称可以解决问题。