我想通过解析excel将数据放入模型中。 models.py是
class User(models.Model):
user_id = models.CharField(max_length=200)
name_id = models.CharField(max_length=200)
age = models.CharField(max_length=200)
man = models.BooleanField()
TYPE_CHOICES = (
('m', 'manager'),
('l', 'leader'),
('o', 'others'),
)
employee =models.CharField(max_length=1, choices=TYPE_CHOICES)
views.py是
#coding:utf-8
from django.shortcuts import render
import xlrd
from .models import User
book = xlrd.open_workbook('../data/data.xlsx')
sheet = book.sheet_by_index(1)
for row_index in range(sheet.nrows):
rows = sheet.row_values(row_index)
def build_employee(employee):
if employee == 'leader':
return 'l'
if employee == 'manager':
return 'm'
if employee == 'others':
return 'o'
for row in rows:
is_man = row[4] != ""
emp = build_employee(rows[5])
user = User(user_id=row[1], name_id=row[2], age=row[3],
man=is_man,employee=emp)
user.save()
我想把m或l或o放到员工模型中,但我无法理解如何通过使用选择字段来完成这项工作。或者我错误地使用选择字段来实现我的目标?
答案 0 :(得分:0)
您需要添加函数,将返回的内容,准备粘贴到DB中的员工变量。像这样:
def build_employee(employee):
if employee == 'leader':
return 'l'
if employee == 'manager':
return 'm'
if employee == 'others':
return 'o'
并在您的方法中调用它:
for row in rows:
is_man = row[4] != ""
emp = build_employee(row[4])
user = User(user_id=row[1], name_id=row[2], age=row[3],
man=is_man,employee=emp)
user.save()