0

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    

fd3s
  • 1
  • 1
  • Seems like I still need to round the number, and I ended up calling cBalance still in html, so not sure if I need to use the 'amount__sum' – fd3s Nov 14 '20 at 00:00

1 Answers1

0

Maybe you could try this :

from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse

class TranListView(ListView):
    
    model = transactions
    
    def get_queryset(self):
        return self.model.objects.filter(user_id=self.request.user)
    
    cBalance = transactions.objects.all().aggregate(cBalance=Sum('amount'))
    
    template = loader.get_template('list.html') # put the name of your html file
    
    context = {
        'cBalance': cBalance,
    }
    
    return HttpResponse(template.render(context, request))
keisay
  • 11
  • 1