如何下载CSV格式的自定义查询集


class ExportPlacesView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
       return super(ExportPlacesView, self).dispatch(request, *args, **kwargs)
    def post(self, request, *args, **kwargs):
        print request.POST
        places_list=[]
        pk_list=[]
        if request.POST.get('area_choice')!= "all":
            selected_areas=self.request.POST.getlist('area_choice')
            print selected_areas
            areas = Area.objects.filter(pk__in=selected_areas)
            for area in areas:
                places_list.append(Fizzer.objects.filter(coordinates__intersects=area.polygon))
            for place in places_list:
               for p in place:
                 pk_list.append(p.pk)
            self.places=Fizzer.objects.filter(pk__in=pk_list)
        else:
            self.places=Fizzer.objects.all()
        return self.places

这是我对一个名为Fizzer的模型进行过滤的观点。结果过滤的查询集是sel.places。如何使用html

中的链接下载CSV格式的查询集self.places

生成和返回csv的基本伪代码:

import csv
from django.http import HttpResponse
def csv(self):
   response = HttpResponse(content_type='text/csv')
   filename = u"fizzer.csv"
   response['Content-Disposition'] = u'attachment; filename="{0}"'.format(filename)
   writer = csv.writer(
      response,
      delimiter=';',
      quotechar='"',
      quoting=csv.QUOTE_ALL
   )
   for f in Fizzer.objects.all():
      writer.writerow([f.foo, f.bar])
   return response

主题演讲:

  • 您必须创建text/csv内容类型的HttpResponse对象

  • 使用Python的csv模块生成。csv

  • 将查询集转换为csv值

  • 返回响应

相关内容

  • 没有找到相关文章

最新更新