【问题标题】:AttributeError: 'tuple' object has no attribute 'Name' Django errorAttributeError:“元组”对象没有属性“名称”Django 错误
【发布时间】:2020-06-30 10:39:56
【问题描述】:

所以我正在创建一个 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: 'tuple' 对象没有属性 'Name'

型号:

类任务(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:

类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)

追踪

【问题讨论】:

    标签: django-models django-rest-framework


    【解决方案1】:

    .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,所以应该是:@ 987654327@ 而不是 Name

    【讨论】:

    • 我尝试了你的建议,现在我得到了,= 消息":"意外的数据类型
    • 我的代码应该无法下载 excel 表格,无法正常工作
    • @AshuoshMishra:恐怕这是因为视图包含很多问题。第一个(关于Name 错误现已修复):)
    • @AshuoshMishra:例如对于Image,它应该是ws.write(row_num,2,my_row.Image1.url,font_style)(与Image2 相同),或者别的什么,但不管它是否是FileField,你可以不要将File 添加到 Excel 工作表中...
    • 名称工作正常,请您帮忙,我需要 excel shettl,我按照上述网站的文档遵循了代码
    猜你喜欢
    • 2019-09-25
    • 1970-01-01
    • 2021-03-20
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    相关资源
    最近更新 更多