开发者

Django, Model with "Def Self" value, SUM aggregate not working

开发者 https://www.devze.com 2023-03-15 21:54 出处:网络
I have the following model: class PurchaseOrderLine(models.Model): productcode = models.ForeignKey(OurProduct, on_delete=models.PROTECT)

I have the following model:

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

In my VIEWS.PY I am trying to total the linetotal's:

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

 return HttpResponse(tot)

But it returns FIELDERROR "Cannot resolve keyword 'linetotal' into 开发者_运维技巧field"???

In the query I can replace Sum('linetotal') for Sum('price') and it work fine, but not with the def linetotal(self).


The linetotal property doesn't exist at the database level, so how would the ORM handle it? You need to implement the query using extra:

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

精彩评论

暂无评论...
验证码 换一张
取 消