[Answered ]-Arithimetic operation before aggregation

1👍

Using QuerySet.extra and QuerySet.values_list:

total = Vendas.objects.extra(select={
    'price': 'sum(item_price * purchase_count)'
}).values_list('price', flat=True)[0]

Example:

>>> Vendas.objects.create(item_price='5.0', purchase_count=1)
<Vendas: Vendas object>
>>> Vendas.objects.create(item_price='15.0', purchase_count=5)
<Vendas: Vendas object>
>>> Vendas.objects.extra(select={
...     'price': 'sum(item_price * purchase_count)'
... }).values_list('price', flat=True)[0]
80

1👍

I would add a calculated property to each item and then sum them all in the view if you need that also.

class Vendas(models.Model):
    ''' Contem informacoes sobre venda realizadas. '''

    purchaser_name = models.CharField(max_length=100)
    item_description = models.CharField(max_length=100)
    item_price = models.DecimalField(max_digits=3, decimal_places=1)
    purchase_count = models.IntegerField()
    merchant_address = models.CharField(max_length=100)
    merchant_name = models.CharField(max_length=100)

    def _this_total(self)
        return self.item_price*self.purchase_count
    this_total = property(_this_total)

def success(request):
    ''' Pagina de retorno para quando o arquivo eh carregado com sucesso! '''
    objects = <your query for objects here>
    total = sum([i.this_total for i in objects])
    return render(request, "file_upload/success.html", locals())

Leave a comment