Search code examples
pythondjangoxlwt

how to show username instead of user id using xlwt


Am exporting data to excel using xlwt but the problem that am getting user id in the row user instead of username, how to fix this,, here is the view

def export_buy_and_sell_report_csv(request):
    today_date = date.today()
    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename="BuyAndSellReports_' + str(today_date) + '.xls"'
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('BuyAndSells')
    # Sheet header, first row
    row_num = 0
    font_style = xlwt.XFStyle()
    font_style.font.bold = True
    columns = ['المستخدم', ' القيمة', 'البيان', 'الفئة', 'نوع الحركة', 'التاريخ']
    for col_num in range(len(columns)):
        ws.write(row_num, col_num, columns[col_num], font_style)
    # Sheet body, remaining rows
    font_style = xlwt.XFStyle()
    rows = models.BuyAndSellReport.objects.all().values_list('user', 'amount', 'text', 'move_category', 'move_type',
                                                             'date')
    rows = [[x.strftime("%Y-%m-%d %H:%M") if isinstance(x, datetime.datetime) else x for x in row] for row in
            rows]
    for row in rows:
        row_num += 1
        for col_num in range(len(row)):
            ws.write(row_num, col_num, row[col_num], font_style)
    wb.save(response)
    return response

Solution

  • You probably want to access a specific property of user instead of using a foreign key in values_list.

    Try constructing your query like this:

    rows = models.BuyAndSellReport.objects.all().values_list('user__username', 'amount', 'text', 'move_category', 'move_type',
                                                             'date')