Django Admin中增加匯出CSV功能過程解析
阿新 • • 發佈:2020-01-09
參考https://books.agiliq.com/projects/django-admin-cookbook/en/latest/export.html
在使用Django Admin時,對於列表我們有時需要提供資料匯出功能,如下圖:
增加匯出CSV功能
在Django Admin中每個模型的Admin類(繼承至admin.ModelAdmin),我們可以通過actions增加支援的動作,值為當前類存在的方法名,例如:
....... @admin.register(Issue) class IssueAdmin(admin.ModelAdmin): ...... actions = ['export_as_csv'] # 增加動作,對應相應的方法名 def export_as_csv(self,request,queryset): # 具體的匯出csv方法的實現 pass export_as_csv.short_description = '匯出CSV' # 該動作在admin中的顯示文字
匯出CSV方法詳細實現如下:
def export_as_csv(self,queryset): meta = self.model._meta # 用於確定匯出的檔名,格式為: app名.模型類名 field_names = [field.name for field in meta.fields] # 所有屬性名 response = HttpResponse(content_type='text/csv') # 指定響應內容型別 response['Content-Disposition'] = f'attachment; filename={meta}.csv' response.charset = 'utf-8-sig' # 可選,修改編碼為帶BOM的utf-8格式(Excel開啟不會有亂碼) writer = csv.writer(response) writer.writerow(field_names) # 將屬性名寫入csv for obj in queryset: # 遍歷要匯出的物件列表 row = writer.writerow([getattr(obj,field) for field in field_names]) # 將當前物件的各屬性值寫入csv return response
由於匯出CSV動作可以作為各個模型的通用動作,我們可以封裝成一個Mixin類使用,完整程式碼如下:
import csv from django.contrib import admin from django.http import HttpResponse from .models import Issue class ExportCsvMixin(object): def export_as_csv(self,queryset): meta = self.model._meta field_names = [field.name for field in meta.fields] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = f'attachment; filename={meta}.csv' response.charset = 'utf-8-sig' writer = csv.writer(response) writer.writerow(field_names) for obj in queryset: row = writer.writerow([getattr(obj,field) for field in field_names]) return response export_as_csv.short_description = '匯出CSV' @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','visit') list_filter = ('origin','tags') search_fields = ('key','summary') date_hierarchy = 'created' actions = ['export_as_csv']
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。