在继承mixins.CreateModelMixin后POST接口上传数据时的处理顺序是view–>serializers–>model,在view中可以通过重写crete方法直接读取请求中附带的excl文件后赋值其他字段并插入model
def create(self, request, *args, **kwargs):
f = request.FILES.get('excl_flie')
if f:
wb = xlrd.open_workbook(filename=None, file_contents=f.read())
table = wb.sheets()[0]
rows = table.nrows
for i in range(1, rows):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
row = table.row_values(i)
serializer.validated_data['ba_item_no'] = row[0]
serializer.validated_data['ba_item_all'] = Production.objects.filter(code=row[0])[0]
serializer.validated_data['suplier'] = row[1]
serializer.validated_data['suplier_all'] = Supplier.objects.filter(code=row[1])[0]
serializer.validated_data['req_qty'] = row[2]
serializer.validated_data['req_data'] = row[3]
serializer.validated_data['owner'] = row[4]
serializer.validated_data['owner_all'] = BaOwner.objects.filter(owner_name=row[4])[0]
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
else:
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
f = request.FILES.get(‘excl_flie’)获取请求中的excl文件
wb = xlrd.open_workbook(filename=None, file_contents=f.read())
xlrd的open_workbook方法定义filename时为根据路径读取文件,如果已经获取到文件可以通过设置file_contents参数读取excl内容