Export database data to CSV

Question:

I have managed to develop an export button which allows users to download all approved orders

`def orders_download(request):
response=HttpResponse(content_type='text/csv')
response['Content- 
Disposition']='attachment;filename="all_orders.csv"'
query=Order.objects.all()

writer=csv.writer(response)
writer.writerow(['DESCRIPTION','COST','QUANTITY','TOTAL_COST','CATEGORY','STATUS','DATE_ORDERED'])


return `response

its downloading but not returning all rows as required.
what is it am missing?

have tried looping but its returning one row multiple times

Asked By: Felix

||

Answers:

you should loop to ensure all the rows are written

for rows in query:
        writer.writerow([rows.description,rows.cost,rows.quantity,rows.total_cost,rows.category,rows.status,rows.order_date])
return response
Answered By: Kenneth Githambo

It seems you are writing a single row with the method writerow. Try to change that row with something like this:

fields = ['DESCRIPTION','COST','QUANTITY','TOTAL_COST','CATEGORY','STATUS','DATE_ORDERED']
for row in query:
    writer.writerow([getattr(row, field) for field in fields])
Answered By: gahadzre
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.