思路
关键:django的视图本身返回的是json数据,而pandas本身就可以对json数据形成excel输出。所以,现在的关键是如何拿到需要的json数据?
突破点:filterset还是serializers,都是可以支持手动使用的。
def generate_queryset_excel(queryset, filterset_cls, serializer_cls, request=None):
if request is not None:
# 手动filterset
filterset = filterset_cls(
request.GET,
queryset=queryset,
)
# 手动serializers
ser = serializer_cls(
filterset.qs,
many=True,
)
else:
ser = serializer_cls(
queryset,
many=True,
)
rename_dict = {
field: queryset.model._meta.get_field(field).verbose_name
for field in serializer_cls.Meta.fields
if field in dir(queryset.model)
}
df = pd.json_normalize(ser.data)
df.index += 1
df = df.rename(columns={
**rename_dict,
'version': '版本',
'tab_page_name': '标签页',
'developer_name': '开发人',
'template_type_name': '模板类型',
'requirement_document_files': '需求文档',
'progress_display': '进度',
})
return df
class DownloadUserView(APIView):
def get(self, request):
df = generate_queryset_excel(UserInfoView.queryset, UserInfoFilterSet, UserInfoSerializer, request=request)
io = BytesIO()
df.to_excel(io)
res = HttpResponse(io.getvalue(), content_type='application/octet-stream; charset=UTF-8')
filename = f'用户信息_{get_now_time_str("%Y-%m-%d_%H_%M_%S")}.xlsx'.encode('utf8').decode('ISO-8859-1')
res['Content-Disposition'] = f'attachment; filename={filename}'
return res
标签:field,df,request,queryset,视图,django,数据表,filterset,cls
From: https://www.cnblogs.com/aiyablog/p/18028613