我正在使用xlwt
将数据导出到excel,但问题是在行用户而不是用户名中获取用户ID,如何解决此问题,这是视图
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
答案 0 :(得分:1)
您可能要访问用户的特定属性,而不是在values_list中使用外键。
尝试像这样构造查询:
rows = models.BuyAndSellReport.objects.all().values_list('user__username', 'amount', 'text', 'move_category', 'move_type',
'date')