我应该如何连接字典的user_id&模型的user_id? [英] How should I connect dictionary's user_id & model's user_id?
问题描述
我想解析excel&制作字典并连接具有相同user_id字典的model(User).现在字典是
I wanna parse excel& make dictionary and connect the model(User) which has same user_id of dictionary. Now dictionary is
dict_data = {'user_id': 1,'nationarity': America, 'dormitory':'A', 'group': 3}
views.py中的模型是
Models in views.py is
user = User(user_id=rows[1],name_id=rows[2],age=rows[3],employee=rows[4])
如果我想将字典的数据添加到模型中,我应该写为
If I wanna add dictionary's data to model,I should write like
for data in dict_data:
User(**data)
但是我应该如何连接字典的user_id&模特的一个?我该怎么写?
but how should I connect dictionary's user_id& models' one?What should I write it?
现在我写得像
#coding:utf-8
from django.shortcuts import render
import xlrd
from app.models import User
book3 = xlrd.open_workbook('./data/XXX.xlsx')
sheet3 = book3.sheet_by_index(0)
headers = sheet3.row_values(0)
large_item = None
dicts = {}
for row_index in range(sheet3.nrows):
rows3 = sheet3.row_values(row_index)
large_item = rows3[1] or large_item
# Create dict with headers and row values
row_data = {}
for idx_col, value in enumerate(rows3):
header_value = headers[idx_col]
# Avoid to add empty column. A column in your example
if header_value:
row_data[headers[idx_col]] = value
# Add row_data to your data_dict with
dicts[row_index] = row_data
for data in dicts:
user1 = User.objects.filer(user_id = data['user_id']).exists()
if user1:
user1.__dict__.update(**dicts)
user1.save()
当我运行这段代码时,
AttributeError: 'Manager' object has no attribute 'filer'
user1 = User.objects.filer(user_id = data['user_id']).exists()
我该如何解决?
推荐答案
dict_data
是dict,不应像列表一样对其进行迭代.我猜你的 dict_data
是字典的列表,所以:
dict_data
you posted is a dict,you shouldn't iterate it like a list.
I guess your dict_data
is a list of dict, so:
for data in dict_datas:
user = User.objects.get(user_id=data['user_id'])
user.name_id = data['**']
...
user.save()
首先,在xecel& dict中使用 user_id
提取用户对象,然后更改值并保存.
First, fetch the user object with user_id
in your xecel&dict, then change the value, and save it.
这篇关于我应该如何连接字典的user_id&模型的user_id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!