Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django models sum 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 query to select all rows in Invoice and the sum of the price of all the items for each invoice, and access it through a queryset

e.g. so if invoice #1 has 2 items, each with qty=2 and unit_price=3, invoice #1 would have amount 2x2x3 = $12

UPDATE:

Here is what I have so far but it gives me a traceback

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 inputs, I took some queues and in the end I created a new column unit_amount, added an extra action to the .save() method to do prod_qty * unit_price and save it to the new column.

and then did this:

inv_list = Invoice.objects.all()\
.annotate(amount=Sum('item__unit_amount')).order_by('-inv_date')
like image 924
bash- Avatar asked Oct 11 '11 12:10

bash-


1 Answers

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
like image 144
infrared Avatar answered Nov 15 '22 09:11

infrared