'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:[1]

Change the sales_total func:

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

More info: https://docs.djangoproject.com/en/4.0/topics/db/aggregation/#cheat-sheet

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ??????? ??????