聚合前的算术运算

时间:2014-02-25 02:40:36

标签: python django orm aggregate

我的models.py中有这个表:

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 success(request):
    ''' Pagina de retorno para quando o arquivo eh carregado com sucesso! '''

    total = ....
    return render(request, "file_upload/success.html", locals())

在我看来,我需要将字段item_pricepurchase_count相乘,然后再添加SUM字段。

在SQL中,它类似于SELECT SUM(item_price*purchase_count) FROM Vendas;,但使用objects.raw也无效。

有人可以帮我吗?

提前致谢!

2 个答案:

答案 0 :(得分:1)

我会为每个项目添加一个计算属性,然后在视图中将它们全部加起来。如果你也需要它。

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())

答案 1 :(得分:1)

使用QuerySet.extraQuerySet.values_list

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

示例:

>>> 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