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')
bash- source
share