Sumproduct Using Django Aggregation

Question

Background

I am simulating an invoice that may contain multiple items. The many-to-many relationship between the Invoice and Element models is processed through the InvoiceItem sub-invoice table.

The total invoice amount is amount_invoicedcalculated by summing the product unit_priceand quantityfor each item on this account. Below is the code I'm currently using to accomplish this, but I was wondering if there is a better way to handle this using the Django Aggregation Capabilities .

Current code

class Item(models.Model):
    item_num = models.SlugField(unique=True)
    description = models.CharField(blank=True, max_length=100)


class InvoiceItem(models.Model):
    item = models.ForeignKey(Item)
    invoice = models.ForeignKey('Invoice')
    unit_price = models.DecimalField(max_digits=10, decimal_places=2)
    quantity = models.DecimalField(max_digits=10, decimal_places=4)


class Invoice(models.Model):
    invoice_num = models.SlugField(max_length=25)
    invoice_items = models.ManyToManyField(Item,through='InvoiceItem')

    def _get_amount_invoiced(self):
        invoice_items = self.invoiceitem_set.all()
        amount_invoiced = 0
        for invoice_item in invoice_items:
            amount_invoiced += (invoice_item.unit_price *
                invoice_item.quantity)
        return amount_invoiced

    amount_invoiced = property(_get_amount_invoiced)        
+3
1

, Django 1.1, . :

 def _get_amount_invoiced(self):
     self.invoiceitem_set.extra(select=("item_total": "quantity * unit_price")
                                ).aggregate(total=Sum("item_total")["total"]

, item_total , , , .

+2

Source: https://habr.com/ru/post/1739058/


All Articles