Product of two fields annotation

后端 未结 2 1162
情话喂你
情话喂你 2021-01-18 17:00

I currently have a line in my Django app like this:

db.execute(\"SELECT SUM(price * qty) FROM inventory_orderline WHERE order_id = %s\", [self.id])


        
相关标签:
2条回答
  • 2021-01-18 17:14

    Unfortunately, there aren't enough inbuilt Aggregate functions and specifically, there is not one for Product.

    But that doesn't limit you in any way other than having to write a "non-concise" ORM query. Specifically for your case, you should be able to do:

    self.line_items.extra(select=("lineprice": "orderline__price*orderline__qty")).aggregate(Sum('lineprice'))
    
    0 讨论(0)
  • 2021-01-18 17:36

    It's not clearly documented, but this can be done with the F() function:

    from django.db.models import F
    
    self.line_items.annotate(lineprice=F('orderline__price') * F('orderline__qty')).aggregate(Sum('lineprice'))
    
    0 讨论(0)
提交回复
热议问题