Hi I am writing a Django view which generates a csv file. Pretty straightforward. In my view I have:
def mysearch(request, exportCSV):
...
if 'q' in request.GET or exportCSV:
results_list = request.session['results_list']
...
if exportCSV:
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=myfile.csv'
writer = csv.writer(response)
# write field titles
writer.writerow(['name_of_firstfield', 'name_of_secondfield', ... ,])
for row in results_list:
# write row content
writer.writerow([row.firstfield, row.secondfield, ... , ])
return response
There are actually two questions here:
How do I output the name of a model field as text so I can write the field titles to the first row.
How can I avoid specifying each field (considering I have a lot of fields) for both lines. I basically want to say for each row, output each field name then output each piece of data.
Can I somehow use getattr here?.