我收到错误TypeError:字符串索引必须是整数.Traceback说
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/XXX/testapp/app/views.py", line 164, in <module>
user1 = User.objects.filter(user_id=row_data['user_id']).exists()
TypeError: string indices must be integers
我写了
#coding:utf-8
from django.shortcuts import render
import xlrd
from .models import User
book = xlrd.open_workbook('../data/excel1.xlsx')
sheet = book.sheet_by_index(1)
def build_employee(employee):
if employee == 'leader':
return 'l'
if employee == 'manager':
return 'm'
if employee == 'others':
return 'o'
for row_index in range(sheet.nrows):
rows = sheet.row_values(row_index)
is_man = rows[4] != ""
emp = build_employee(rows[5])
user = User(user_id=rows[1], name_id=rows[2], name=rows[3],
age=rows[4],man=is_man,employee=emp)
user.save()
files = glob.glob('./user/*.xlsx')
for x in files:
if "$" not in x:
book3 = xlrd.open_workbook(x)
sheet3 = book3.sheet_by_index(0)
cells = [
]
data_dict = OrderedDict()
for key, rowy, colx in cells:
try:
data_dict[key] = sheet3.cell_value(rowy, colx)
except IndexError:
data_dict[key] = None
for row_number, row_data in data_dict.items():
user1 = User.objects.filter(user_id=row_data['user_id']).exists()
if user1:
user1.__dict__.update(**data_dict)
user1.save()
我真的不明白为什么会发生这个错误,因为我知道data_dict是字典类型,所以我使用items()进行迭代。我也无法理解哪些索引必须是整数。我怎么能解决这个问题?我该怎么写呢? data_dict就像
OrderedDict([('user_id', '1'), ('name', 'Blear'), ('nationality', 'America'), ('domitory', 'A'), ('group', 1)], [('user_id', '1'), ('name', 'Blear'), ('nationality', 'America'), ('domitory', 'A'), ('group', 1)], [('user_id', '1'), ('name', 'Blear'), ('nationality', 'America'), ('domitory', 'A'), ('group', 1)])