Currently using aggregation for the first time, attempting to get a sum of all 'transactions' and display them on my HTML page. I am using generic class based views, currently in my function it is displaying transactions that are created by the user. I am able to display the cBalance if I return it from a function, although my 'display only the user created transactions' function should take priority. I am trying to get my cBalance to be displayed in HTML Here is my function in views.py
class TranListView (ListView):
model = transactions
def get_queryset(self): #gets only if user matches
return self.model.objects.filter(user_id=self.request.user)
#def get_context_data(self):
# cBalance = transactions.objects.all().aggregate(cBalance=Sum('amount'))
# return cBalance
List Template:
<ul>
<a href="{% url 'landing' %}"> Homepage</a><br><br>
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'taction-create' %}">Create New</a>
<h5> Transactions: </h5>
<li> {{ cBalance }}</li>
{% for object in object_list %}
<li>{{ object.tname }}</li>
<li>{{ object.amount }}</li>
<li>{{ object.date }}</li>
<li>{{ object.recipient }}</li>
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'taction-update' object.id %}">Update</a>
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'taction-delete' object.id %}">Delete</a>
<hr/>
{% empty %}
<li>No objects yet.</li>
{% endfor %}
</ul>
If anyone can help me out it'd be greatly appreciated
Edit: got it working with this
class TranListView (ListView):
model = transactions
def get_queryset(self): #gets only if user matches
return self.model.objects.filter(user_id=self.request.user)
def get_context_data(self, *args, **kwargs):
context = super(TranListView, self).get_context_data(*args, **kwargs)
context['cBalance'] = transactions.objects.filter(user_id=self.request.user).aggregate(Sum('amount'))['amount__sum'] or 0.00
return context