如何将Django模型数据导出到CSV文件

如何将Django模型数据导出到CSV文件,第1张

如何将Django模型数据导出到CSV文件

我通常更喜欢在管理员中执行此 *** 作。这是片段

def download_csv(modeladmin, request, queryset):    if not request.user.is_staff:        raise PermissionDenied    opts = queryset.model._meta    model = queryset.model    response = HttpResponse(mimetype='text/csv')    # force download.    response['Content-Disposition'] = 'attachment;filename=export.csv'    # the csv writer    writer = csv.writer(response)    field_names = [field.name for field in opts.fields]    # Write a first row with header information    writer.writerow(field_names)    # Write data rows    for obj in queryset:        writer.writerow([getattr(obj, field) for field in field_names])    return responsedownload_csv.short_description = "Download selected as csv"

在您的视图功能中使用它

def myview(request):    data = download_csv(ModelAdmin, request, Model.objects.all())    return HttpResponse (data, content_type='text/csv')


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5664566.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存