7

So I'm making an expense sheet django app and I'm stuck trying to render the Sum of all the inputted expenses.

I've created a custom manager to calculate the sum:

class ExpenseManager(models.Manager):
  def price_sum(self):
    return super(ExpenseManager, self).aggregate(total_price = Sum('price'))['total_price']

And added it to my model:

class Expense(models.Model):
  ...
  objects = models.Manager()
  price_object = ExpenseManager()
  ...

I know my manager works because when I execute it in the shell I get the correct sum of my expenses -- i.e. I put in Expense.price_object.price_sum() and I get back Decimal('254.77') -- but when I try to get that into my template it just shows up blank.

I've tried putting in my variable a couple different ways but none of it has worked, for example:

{{price_object.price_sum}}

or

{{expense.price_object.price_sum}}

or me getting desperate...

{% for p in expense.price_object %} {{p.price_sum}} {% endfor %}

or

{% for p in expense.price_object.price_sum %} {{p}} {% endfor %}

but yeah... nothing ever shows up when I load the page. Can anyone help?

2 Answers2

1

Try to define your manager method like this:

class ExpenseManager(models.Manager):
    def get_expenses(self):
        return super(ExpenseManager, self).get_query_set().aggregate(total_price = Sum('interval'))['total_price']

I just tried it and it calculated the sum in a template for me.

dragoon
  • 5,601
  • 5
  • 37
  • 55
1

None of your template examples seem to be equivalent to what you did in the shell. In the shell, you correctly called the manager from the model class, Expense. That's exactly what you need to do from the template as well. You can't call it from a model instance, only the class, and I assume that the expense name you have there is an instance. You'll need to pass the class itself to the template context.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Sorry if this is basic, but how do you pass the class itself? currently in my view I pass `all_expenses = Expense.objects.all()` as the context as `{'expenses':all_expenses}` (I changed the variable from expense to expenses since it does account for all the expenses rather than one so that's not a problem in comparison to what I shared above) –  Jul 16 '13 at 17:50
  • A class is an object, like anything else. You can pass it in exactly the same way: `{'Expense': Expense}`. – Daniel Roseman Jul 17 '13 at 08:27