Django Admin中增加導(dǎo)出Excel功能過程解析
在使用Django Admin時, 對于列表我們有時需要提供數(shù)據(jù)導(dǎo)出功能, 如下圖:
增加導(dǎo)出Excel功能

在Django Admin中每個模型的Admin類(繼承至admin.ModelAdmin), 我們可以通過actions增加支持的動作, 值為當(dāng)前類存在的方法名, 例如:
.......
@admin.register(Issue)
class IssueAdmin(admin.ModelAdmin):
......
actions = ['export_as_excel'] # 增加動作, 對應(yīng)相應(yīng)的方法名
def export_as_csv(self, request, queryset): # 具體的導(dǎo)出csv方法的實現(xiàn)
pass
export_as_excel.short_description = '導(dǎo)出Excel' # 該動作在admin中的顯示文字
導(dǎo)出Excel方法詳細(xì)實現(xiàn)如下:
from openpyxl import Workbook
....
def export_as_excel(self, request, queryset):
meta = self.model._meta # 用于定義文件名, 格式為: app名.模型類名
field_names = [field.name for field in meta.fields] # 模型所有字段名
response = HttpResponse(content_type='application/msexcel') # 定義響應(yīng)內(nèi)容類型
response['Content-Disposition'] = f'attachment; filename={meta}.xlsx' # 定義響應(yīng)數(shù)據(jù)格式
wb = Workbook() # 新建Workbook
ws = wb.active # 使用當(dāng)前活動的Sheet表
ws.append(field_names) # 將模型字段名作為標(biāo)題寫入第一行
for obj in queryset: # 遍歷選擇的對象列表
for field in field_names:
data = [f'{getattr(obj, field)}' for field in field_names] # 將模型屬性值的文本格式組成列表
row = ws.append(data) # 寫入模型屬性值
wb.save(response) # 將數(shù)據(jù)存入響應(yīng)內(nèi)容
return response
由于導(dǎo)出Excel動作可以作為各個模型的通用動作, 我們可以封裝成一個Mixin類使用, 完整代碼如下:
from openpyxl import Workbook
from django.contrib import admin
from django.http import HttpResponse
from .models import Issue
class ExportExcelMixin(object):
def export_as_excel(self, request, queryset):
meta = self.model._meta
field_names = [field.name for field in meta.fields]
response = HttpResponse(content_type='application/msexcel')
response['Content-Disposition'] = f'attachment; filename={meta}.xlsx'
wb = Workbook()
ws = wb.active
ws.append(field_names)
for obj in queryset:
for field in field_names:
data = [f'{getattr(obj, field)}' for field in field_names]
row = ws.append(data)
wb.save(response)
return response
export_as_excel.short_description = '導(dǎo)出Excel'
@admin.register(Issue)
class IssueAdmin(admin.ModelAdmin, ExportCsvMixin):
fields = ('key', 'summary', 'status', 'project',
'origin', 'components', 'prj_level', 'prj_category',
'assignee', 'origin_person', 'pm', 'dev_manager', 'test_manager', 'tester', 'fe_dev', 'backend_dev',
'plan_begin', 'plan_end', 'fe_plan_begin', 'fe_plan_end', 'test_plan_begin',
'test_plan_end', 'backend_plan_begin', 'backend_plan_end',
'created', 'reopen', 'prd_begin', 'prd_end', 'dev_begin', 'dev_end',
'test_begin', 'test_end', 'pm_check', 'ready', 'pause', 'done',
'pm_take', 'dev_take', 'test_take', 'total_take',
'tags',
)
readonly_fields = fields
list_display = ('key', 'summary', 'status', 'origin', 'components', 'created', 'visit')
list_filter = ('origin', 'components', 'status', 'tags')
search_fields = ('key', 'summary')
date_hierarchy = 'created'
actions = ['export_as_excel']
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python中random模塊生成隨機(jī)數(shù)詳解
本文給大家匯總了一下在Python中random模塊中最常用的生成隨機(jī)數(shù)的方法,有需要的小伙伴可以參考下2016-03-03
django與小程序?qū)崿F(xiàn)登錄驗證功能的示例代碼
這篇文章主要介紹了django與小程序?qū)崿F(xiàn)登錄驗證功能的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-02-02
Python?虛擬機(jī)字典dict內(nèi)存優(yōu)化方法解析
這篇文章主要為大家介紹了Python?虛擬機(jī)字典dict內(nèi)存優(yōu)化方法解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
Python日志打印里logging.getLogger源碼分析詳解
在本篇文章里小編給大家整理的是一篇關(guān)于Python logging.getLogger源碼分析的相關(guān)內(nèi)容,有興趣的朋友們可以學(xué)習(xí)參考下。2021-01-01

