Django,具有“Def Self”值的模型,SUM聚合不起作用

时间:2011-06-25 21:35:41

标签: python django sum aggregate

我有以下型号:

class PurchaseOrderLine(models.Model):

 productcode = models.ForeignKey(OurProduct, on_delete=models.PROTECT)

 price = models.DecimalField (max_digits=6, decimal_places=2)

 qty = models.IntegerField()


 def linetotal(self):

    from decimal import *

    total = (self.price * self.qty)

    return total

在我的VIEWS.PY中,我试图计算总线数:

 tot=PurchaseOrderLine.objects.aggregate(total=Sum('linetotal'))['total'] 

 return HttpResponse(tot)

但它返回FIELDERROR“无法将关键字'linetotal'解析为字段”???

在查询中,我可以将Sum('linetotal')替换为Sum('price'),它可以正常工作,但不能使用def linetotal(self)。

1 个答案:

答案 0 :(得分:1)

linetotal属性在数据库级别不存在,那么ORM将如何处理它?您需要使用extra实现查询:

for purchase_order_line in PurchaseOrderLine.objects.extra(select={'total': 'price * qty'}):
    print purchase_order.total
相关问题