所以我正在创建一个api:只是简单地将某个模型导出到xls中。我根据文档进行了设置, https://www.pythoncircle.com/post/190/how-to-download-data-as-csv-and-excel-file-in-django/#:~:text=Download%20data%20as%20Excel%20file%20in%20Django%3A&text=It%20is%20always%20recommended%20to,command%20to%20add%20xlwt%20package.&text=Inside%20your%20view%2C%20import%20xlwt,create%20and%20download%20excel%20file.but运行时出现此错误:
AttributeError:“元组”对象没有属性“名称”
型号:
Class Task(models.Model)
Id=models.IntegerField()
Name=models.CharField(max_length=50,null=False,blank=True)
Image1=models.FileField(blank=True, default="",
upload_to="media/images",null=True)
Image2=models.FileField(blank=True, default="",
upload_to="media/images",null=True)
Date=models.DateField(null=True,blank=True)
def __str__(self):
return str(self.Name)
#viewset:
Class TaskViewSet(viewsets.ViewSet):
def list(self, request):
try:
response=HttpResponse(content_type='application/ms-excel')
response['Content-Disposition']='attachment; filename="users.xls"'
wb=xlwt.Workbook(encoding='utf-8')
ws=wb.add_sheet('Tasks')
row_num=0
font_style=xlwt.XFStyle()
font_style.font.bold=True
columns=['Id','Name','Image1','Image2','Date']
for col_num in range(len(columns)):
ws.write(row_num,col_num,columns[col_num],font_style)
font_style=xlwt.XFStyle()
data=Task.objects.all().values_list('Id','Name','Image1','Image2','Date')
for i in data:
print(i.Name)
for my_row in data:
row_num+=1
ws.write(row_num,0,my_row.Id,font_style)
ws.write(row_num,1,my_row.Name,font_style)
ws.write(row_num,2,my_row.Image1,font_style)
ws.write(row_num,3,my_row.Image2,font_style)
ws.write(row_num,4,my_row.Date,font_style)
wb.save(response)
return response
except Exception as error:
traceback.print_exc()
return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK)
Trac
答案 0 :(得分:0)
.values_list
返回一个元组的QuerySet
,因此,要访问Name
字段,请执行以下操作:
data = Task.objects.values_list('Id', 'Name', 'Image1', 'Image2', 'Date')
for i in data:
print(i[1])
但是这里并没有太多理由使用.values_list(…)
。您可以使用以下方法获取对象:
data = Task.objects.all()
for i in data:
print(i.Name)
注意:通常,Django模型中字段的名称是用 snake_case 而不是 PerlCase 编写的,因此应为:{ {1}}代替
。name