Get sales totals per account using model property in django

Okay I thought I can google my way out of this but I am stuck.

Desired results are

 Account_name        Total
 local sales         1802.50
 int sales           0.00

from my models

class Account(models.Model):
    account_number = models.IntegerField(unique=True, null=True, blank=True, default=None)
    account_name   = models.CharField(max_length=200, null=True, blank=True, unique=True)


class Sales(models.Model):
    account_name = models.ForeignKey(Account, on_delete=models.CASCADE, related_name='incomes')
    amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)

    def sales_total(self):
        sales_total = Income.objects.values('account_name').order_by('account_name').annotate(sales_total=Sum('sales__total'))
        return sales_total

So in my template when I do

{% for account in accounts %}
    <tr>      
      <td>{{ account.sales_total }}</td>
    </tr>
{% endfor %}

I get

 Account_name     Total
 local sales      <QuerySet [{'account_name': 3, 'sales_total': Decimal('1802.5')}]>
 int sales        <QuerySet [{'account_name': 3, 'sales_total': Decimal('1802.5')}]>

Solution 1:

So I managed to to this after so much research on the net

in the account model I defined a function to get the sales totals

def sales_total(self):
       return sum([item.sales_total() for item in self.incomes.all()])

The in the template got the values as {{ account.sales_total }}