使用Django从已定义的类生成ZipFile

时间:2018-08-23 10:30:28

标签: python django

我的视图中有2个定义的类,它们生成CSV文件。我想提供一个选项,一次下载一个zip文件中的两个文件,也可以单独下载两个文件。 我在视图中创建了此类,以生成我的ZIP

class ExportInitiativeAssessmentsView(LoginRequiredMixin, ListView):
 model = AssessmentSubmission
 queryset = AssessmentSubmission.objects.filter(assessment__slug__in= . 
 ['init_exec', 'init_registration'])
 def get_queryset(self):
    if self.request.user.is_superuser:
        queryset = self.queryset
    else:
        queryset =

self.queryset.filter(registration__partner_organization = self.request.user.partner)         返回查询集     def get(self,request,* args,** kwargs):

    headers = {
        'registration__youth__first_name': 'First Name',
        'registration__youth__father_name': "Fathers's Name",

    }
    qs = self.get_queryset()..values(
        'registration__youth__first_name',
        'registration__youth__father_name',    
    )

    filename = 'Initiative-Export'
    return render_to_csv_response(qs, filename,  field_header_map=headers)


class ExportPBI(LoginRequiredMixin, ListView):
    file1 = ExportInitiativeAssessmentsView.as_view()  # Class defined above and returned a csv file
    file2 = ExportRegistryAssessmentsView().as_view()  # Class defined above and returned a csv file
    current_files = [file1, file2,]
    zipped_file = StringIO.StringIO()

    with zipfile.ZipFile(zipped_file, 'w') as zip:
        for file in current_files:
            zip.write('Initiative-Export.csv')
    zipped_file.close()

0 个答案:

没有答案