I'm trying to write some search results to a CSV file, but with the ability to have some fields be empty. Right now it's writing the entire search string, but it's the only way I've found to deal with errors when there's no field.
This is my code:
if request.POST.get('search_type_id') == "1":
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="Report Results.csv"'
export_data = request.session['report_results']
report_results = Tree.objects.filter(id__in=[instance['id'] for instance in export_data]).order_by('-created_at')
writer = csv.writer(response)
writer.writerow(['Tree ID', 'Int ID', 'Site Address', 'Site Street', 'Date Planted'])
for obj in report_results:
Try something like this.
writer.writerow([ obj.id_shared or '', obj.id_int or '', obj.planting_site.site_address or '', obj.planting_site.site_street or '', obj.planted_date or '' ])
If the object property is empty, the or condition will result in blank being written to the file