Pedro Mariz
Pedro Mariz

Reputation: 161

Making a query in django and return sum of all my objects

i have this Model

class Invoice(models.Model):
    field1= models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=10)
    amount_field2= models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=10)    
    price_field2= models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=10) 

i can have several Invoice's, so i want to do like (amount_field2*price_field2) and SUM to all Invoices to have a total in the end. i need to do this in my view because i waint to return the total to my template.

Upvotes: 0

Views: 95

Answers (2)

Pavan kumar
Pavan kumar

Reputation: 515

class Invoice(models.Model):
    field1= models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=10)
    amount_field2= models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=10)    
    price_field2= models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=10)

    def single_invoice_total(self):
        return self.amount_field2 * self.price_field2
    def get_total_of_all_invoices(self):
        total = 0
        for single_invoice in self.Invoice.all():
            total += single_invoice.single_invoice_total()
        return total

and you can show it in your template by sending through a view context you can access the total by
{{ Invoice.get_total_of_all_invoices }}

Upvotes: 1

Pedro Mariz
Pedro Mariz

Reputation: 161

already find the solutions:

query = Invoice.objects.aggregate(total= Sum(F('amout_field2') * F('price_field2')),) 

Upvotes: 1

Related Questions