我想解析excel并将其放到具有相同user_id字典的模型(User)中。我写了
if
db.sqlite3在此部分中包含数据
#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')
data_dict_key ={}
for x in files:
if "$" not in x:
book3 = xlrd.open_workbook(x)
sheet3 = book3.sheet_by_index(0)
cells = [
('company_id', 0, 4),
('user_id', 0, 5),
('name', 0, 6),
]
data_dict = OrderedDict()
for key, rowy, colx in cells:
try:
data_dict[key] = sheet3.cell_value(rowy, colx)
except IndexError:
data_dict[key] = None
if data_dict['user_id'] in data_dict_key:
data_dict_key[data_dict['user_id']].update(data_dict)
continue
data_dict[data_dict_key['user_id']] = data_dict
for row_number, row_data in data_dict_key.items():
user1 = User.filter(user_id=row_data['user_id']).exists()
if user1:
user1.__dict__.update(**data_dict_key)
user1.save()
并在此部分
User(user_id=rows[1], name_id=rows[2], name=rows[3],
age=rows[4],man=is_man,employee=emp)
分开。 我想在这部分中使用相同的user_id将这些部分数据保存在一起
user1.__dict__.update(**data_dict_key)
所以我真的无法理解为什么我不能这样做。没有错误发生,所以我没有线索。我的代码出了什么问题?我应该如何解决这个问题? models.py是
User.filter(user_id=row_data['user_id']).exists()
答案 0 :(得分:0)
该行:
user1 = User.filter(user_id=row_data['user_id']).exists()
看起来有误,原因有两个:
filter()
,而不是模型实例,exists()
返回bool 由于filter()
的使用不正确,此代码应引发异常,但事实并非如此,似乎该行未被执行。原因是因为data_dict_key
为空,因此未输入最终for循环的主体。最后data_dict_key
为空的原因是由于此代码中的if
语句:
if data_dict['user_id'] in data_dict_key:
data_dict_key[data_dict['user_id']].update(data_dict)
data_dict_key
在主循环之前初始化为{}
,因此它永远不会包含用户ID的密钥。