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

时间:2016-10-05 20:55:13

标签: django django-models django-admin django-views django-queryset

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的模型的视图。结果过滤的querset为sel.places。如何使用html中的链接以CSV格式下载查询集self.places

1 个答案:

答案 0 :(得分:1)

生成并返回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

注释记号:

  • 您必须使用HttpResponse内容类型

  • 创建text/csv个对象
  • 使用Python的csv模块

  • 生成.csv
  • 将查询集转换为csv值

  • 返回回复