这里是一个视图,我用来下载Excel文档的基础上关闭数据,我有:
class ExcelDownloadAllView(TemplateView):
def get(self, request, *args, **kwargs):
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename="All_of_Projects.xls"'
wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet('All Projects Data') # this will make a sheet named Users Data
# Sheet header, first row
row_num = 0
font_style = xlwt.XFStyle()
font_style.font.bold = True
columns = ['Username', 'First Name', 'Last Name', 'Email Address', 'Summary']
rows = BugTracker.objects.all().values_list('project_number','assignee','priority','status','summary',)
for col_num in range(len(columns)):
ws.write(row_num, col_num, columns[col_num], font_style) # at 0 row 0 column
# Sheet body, remaining rows
font_style = xlwt.XFStyle()
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
它工作得很好,但是现在我想用不同的“row=”过滤器创建另一个CBV。使用DRY原则做这件事的最好方法是什么?
我尝试了类似的方法,但是rows变量会被前面的类覆盖。
class ExcelDownloadOpenView(ExcelDownloadAllView):
def get(self, request, *args, **kwargs):
rows = BugTracker.objects.all().values_list('project_number','assignee', 'priority')
return super().get(request, *args, **kwargs)
在不复制整个方法和替换rows变量的情况下,有什么建议吗?
1条答案
按热度按时间huwehgph1#
编写一个函数来创建一个文件并将其附加到响应中,并将此函数放在外部文件中以清理代码。例如,假设一个名为
core
的模块(app):utils.py
views.py: