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}
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)
but how should I connect dictionary's user_id& models' one?What should I write it?
Now I wrote like
#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()
When I run this code,
AttributeError: 'Manager' object has no attribute 'filer'
user1 = User.objects.filer(user_id = data['user_id']).exists()
How should I fix this?
for data in dict_datas:
user = User.object.filter(user_id = data['user_id']).exists()
if user:
user.__dict__.update(**dict_data)
user.save()
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()
First, fetch the user object with user_id
in your xecel&dict, then change the value, and save it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.