User manager function call in django templates

So, I am making a django application for an expense schedule, and I am stuck trying to display the sum of all inputted costs.

I created a user manager to calculate the amount:

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 that my manager works because when I execute it in the shell I get the correct amount of my expenses, that is, I put in Expense.price_object.price_sum() and I return Decimal('254.77') - but when I am trying to get this in my template just showing empty.

I tried putting several different methods into my variable, but none of them worked, for example:

 {{price_object.price_sum}} 

or

 {{expense.price_object.price_sum}} 

or me desperately ...

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

or

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

but yes ... nothing appears when I load the page. Can anyone help?

+6
source share
2 answers

Try defining your manager’s method as follows:

 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 amount in the template for me.

+1
source

None of your sample templates match what you did in the shell. In the shell, you correctly called the manager from the Expense model class. This is what you need to do from the template. You cannot call it from an instance of a model, just a class, and I assume that you have an Expense name instance. You need to pass the class itself to the template context.

+1
source

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


All Articles