Django models summation field from foreign key relationship

I have a one to many relationship.

class Invoice(models.Model):
    stuff

class Item(models.Model):
    invoice = models.ForeignKey(Invoice)
    qty = models.IntegerField()
    unit_price = models.DecimalField(max_digits=4, decimal_places=2)

I want to make a request to select all the lines in the invoice and the sum of the price of all elements for each invoice and to access it through the request

eg. so if you invoice #1have 2 items, each with qty=2and unit_price=3, invoice #1would haveamount 2x2x3 = $12

UPDATE:

Here is what I have, but it gives me a trace

inv_list = \
Invoice.objects.select_related().all()\
.aggregate(sum=sum('item__unit_price')).order_by('-inv_date')

TypeError at /site/invoice/
unsupported operand type(s) for +: 'int' and 'str'

UPDATE

Thanks for the input, I took a few queues and eventually created a new column unit_amount, added an extra action to the method .save()to do prod_qty * unit_priceand save it to a new column.

and then did the following:

inv_list = Invoice.objects.all()\
.annotate(amount=Sum('item__unit_amount')).order_by('-inv_date')
+5
source share
3

select_related(), , .aggregate(sum=sum('unit_price')), ? select_related() .

aggregate {sum:value}, ? ? .:)

, ?

for invoice in Invoice.objects.all():
    tmp = invoice.item_set.aggregate(sum=sum('unit_price'))
    # do some stuff with sum

, -, . .

//EDIT: , . .

+2
for invoice in Invoice.objects.all():
    ammount = 0
    for item in invoice.item_set.all():
        ammount += item.qty * item.unit_price
        print invoice.pk, ammount
+2

F() Django 1.8 :

from django.db.models import F, Sum

Invoice.objects.annotate(Sum(F('item__unit_price') * F('item__qty')))
+2

All Articles