import tempfile
with tempfile.TemporaryFile() as tmp:
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED) as archive:
data = []
count = 1
for item in (self._iter_csv_rows(
queryset=self._get_changelist_instance(request).get_queryset(request), charset=charset)):
data.append(item)
if len(data) >= 10000:
tmp2 = tempfile.TemporaryFile()
#csv作成
writer = csv.writer(tmp2)
writer.writerows(data)
tmp2.seek(0)
archive.writestr('{}-{}.csv'.format(self.model._meta.model_name,count), tmp2.read())
count += 1
data = []
tmp2.close()
tmp.seek(0)
res = HttpResponse(tmp.read(), content_type='application/x-zip-compressed')
res['Content-Disposition'] = 'attachment; filename={base}_{dt}.zip'.format(
base=self.model._meta.model_name,
dt=datetime.now().strftime('%Y%m%d-%H%M%S'))
res['Pragma'] = 'public'
res['Cache-Control'] = 'public'
return res
More than 5 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme