1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| from django.db.models import Q from django.http import StreamingHttpResponse
from sample.models import Bicycle
def export_csv(request): heads = ('bicycle_num', 'bicycle_type', 'body_num', 'platform_qrcode', 'put_status', 'bicycle_qrcode', 'created_time',)
def query_data(): q = Q() limit, offset = 10000, 0 while True: bicycles = Bicycle.objects.filter(q).values(*heads)[offset: offset + limit] if len(bicycles) == 0: break yield bicycles offset += limit
def _to_csv(): yield ','.join(heads) + '\n' for data in query_data(): for row in data: yield ','.join([f'"{row[head]}"' for head in heads]) + '\n'
return StreamingHttpResponse(_to_csv(), headers={ 'content_type': 'application/csv', 'content-disposition': 'attachment; filename=export.csv', })
|