Jason Boyce Jason Boyce - 1 year ago 68
Python Question

Django write to csv with some empty fields

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:
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:
[obj.id_shared, ''],
[obj.id_int, ''],
[obj.planting_site.site_address, ''],
[obj.planting_site.site_street, ''],
[obj.planted_date, '']
return response

Right now my CSV returns accounts for empty fields, but gives me a [250264, ''] as the Tree ID, for example. Is there a way I can tell it to substitute blank if there's nothing (fore xample, no obj.planting_site.site_address)?

In doing this for JSON results pulled from another site I've been doing obj.get('tree_id', ''), but I can't do that when the objects are models saved internally.

Answer Source

Try something like this.

                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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download