1、前端增加下载按钮
<a href="/dump_orders/" class="btn btn-primary" style="margin-bottom:20px">导出数据</a>
2、url.py中配置路由
path("dump_orders/", views_order.dump_orders),
3、views.py中编写view函数
def dump_orders(request):
datas = OrderData.objects.all()[:3]
print(datas.values())
df = pd.DataFrame.from_records(datas.values())
df.rename(columns={"number":"编号"}, inplace=True)
print(df.head(5))
curtime = int(time.time())
filename = f"orderdata_{curtime}.csv"
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
df.to_csv(path_or_buf=response, index=False)
return response
几点说明:
1、django的mysql查询结果,怎样转换成pd.DataFrame
datas = OrderData.objects.all()[:3]
print(datas.values())
df = pd.DataFrame.from_records(datas.values())
其中,datas.values()是这样的格式:
<QuerySet [{'id': 1, 'number': 6123001, 'name': '背包', 'chenbenjia': 16, 'xiaoshoujia': 65, 'xiaoshoushuliang': 600, 'chanpinchengben': 9600, 'xiaoshoushouru': 39000, 'xiaoshoulirun': 29400}, {'id': 2, 'number': 6123004, 'name': '背包', 'chenbenjia': 16, 'xiaoshoujia': 65, 'xiaoshoushuliang': 230, 'chanpinchengben': 3680, 'xiaoshoushouru': 14950, 'xiaoshoulirun': 11270}, {'id': 3, 'number': 6123009, 'name': '背包', 'chenbenjia': 16, 'xiaoshoujia': 65, 'xiaoshoushuliang': 250, 'chanpinchengben': 4000, 'xiaoshoushouru': 16250, 'xiaoshoulirun': 12250}]>
类似一个list,里面的每个条目,都是key=value的形式;
而pd.DataFrame.from_records,可以从这样的格式,得到一个dataframe
id 编号 name chenbenjia xiaoshoujia xiaoshoushuliang chanpinchengben xiaoshoushouru xiaoshoulirun
0 1 6123001 背包 16 65 600 9600 39000 29400
1 2 6123004 背包 16 65 230 3680 14950 11270
2 3 6123009 背包 16 65 250 4000 16250 12250
2、怎样给前端输出csv文件
filename = f"orderdata_{curtime}.csv"
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
df.to_csv(path_or_buf=response, index=False)
其中df.to_csv有个参数,path_or_buf=response两者可以结合起来。
最终的效果,页面点击按钮,实现查询mysql,文件下载。