Skip to content

Instantly share code, notes, and snippets.

@DevanR
Last active January 7, 2019 09:49
Show Gist options
  • Save DevanR/3b1cf72e8120587586f04ba401e6be6d to your computer and use it in GitHub Desktop.
Save DevanR/3b1cf72e8120587586f04ba401e6be6d to your computer and use it in GitHub Desktop.
Read csv into dict
class ExportOrder(SpecificRoleRequiredMixin, View):
allowed_roles = [SALES_ADMIN, SALES_USER]
def get(self, request, *args, **kwargs):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="wholesale_billing.csv"'
orders = Order.objects.all().order_by('created_on')
field_mapping = OrderedDict([
# CSV header: Order model field,
('reference', 'reference'),
('billing_date', 'delivery_date'),
('circuit_reference', 'ead_circuit_ref'),
('data_rate', 'service_data_rate'),
('bearer_rate', 'service_access_rate'),
('contract_term', 'service_term_months'),
('end_customer', 'customer_name'),
('site_name', 'site_address_name'),
('address', [
'site_address_street',
'site_address_city',
'site_address_county',
'site_address_postcode',
]),
('distance', 'service_mainlink_distance'),
('connection_type', 'service_type'),
('costs_currency', 'costs_currency'),
('costs_distance_charge', 'costs_distance_charge'),
('costs_connection_charge', 'costs_connection_charge'),
('costs_connection_total', 'costs_connection_total'),
('costs_connection_discount_method', 'costs_connection_discount_method'),
('costs_connection_discount_value', 'costs_connection_discount_value'),
('costs_rental_charge', 'costs_rental_charge'),
('costs_rental_total', 'costs_rental_total'),
('costs_rental_discount_method', 'costs_rental_discount_method'),
('costs_rental_discount_value', 'costs_rental_discount_value'),
('ecc_costs', 'third_party_costs_ecc'),
('trc_costs', 'third_party_costs_trc'),
('mdf_code', 'service_local_exchange_code'),
])
export_data = []
for order in orders:
order_dict = OrderedDict()
for header, model_field in field_mapping.iteritems():
if isinstance(model_field, list):
value = ", ".join([getattr(order, f) for f in model_field])
else:
value = getattr(order, model_field)
order_dict[header] = value
export_data.append(order_dict)
if not export_data:
writer = csv.writer(response)
writer.writerow(['no orders found'])
else:
dict_writer = csv.DictWriter(response, export_data[0].keys())
dict_writer.writeheader()
dict_writer.writerows(export_data)
return response
export_order = ExportOrder.as_view()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment