Reputation: 12064
I want to be able to convert some Django model to a Excel file. My view is as follows:
@login_required
def archive_to_excel(request):
calculations_list = Calculations.objects.filter(user=request.user) \
.values_list('make', 'model', 'first_registration', 'body', 'facelift',
'engine', 'transmission', 'purchase_price', 'mileage',
'customer__firstname', 'customer__lastname', 'customer__email') \
.order_by('-id')
columns = [_('Make'), _('Model'), _('First registration'), _('Body'), _('Facelift'), _('Engine'), _('Transmission'),
_('Price'), _('Mileage'), _('Customer first name'), _('Customer last name'), _('Customer email')]
return convert_to_excel("archive", columns, calculations_list)
And convert_to_excel
function is as follows:
def convert_to_excel(file_name, columns, values):
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename="{}.xls"'.format(file_name)
wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet(file_name.capitalize())
# Sheet header, first row
row_num = 0
font_style = xlwt.XFStyle()
font_style.font.bold = True
for col_num in range(len(columns)):
ws.write(row_num, col_num, columns[col_num], font_style)
# Sheet body, remaining rows
font_style = xlwt.XFStyle()
for row in values:
row_num += 1
for col_num in range(len(row)):
ws.write(row_num, col_num, row[col_num], font_style)
wb.save(response)
return response
That works fine, but the problem that I have is that the purchase_price
in Calculations
model is stored EXCL VAT and I want to show it in the excel file INCL VAT.
How can I multiply the purchase_price
with 1.21 and show it in the excel file?
Any advice?
Upvotes: 0
Views: 653
Reputation: 3100
You can for instance do this:
calculations_list = Calculations.objects.filter(user=request.user) \
.values_list('make', 'model', 'first_registration', 'body', 'facelift',
'engine', 'transmission', 'mileage',
'customer__firstname', 'customer__lastname', 'customer__email') \
.annotate(purchase_price=F('purchase_price')*1.21)
.order_by('-id')
Upvotes: 1