Home > Software design >  How do i do the summation of two dictionary with aggregate in django , and show it in HTML?
How do i do the summation of two dictionary with aggregate in django , and show it in HTML?

Time:07-10

i am new to django , would u experts pls kindly help me..

so i have two modules, and in CBV's get_context_data they both return total sum, now I want to add both the totals and display it on my HTML page, I honestly tried many things but I am always getting an error.

here is my views.py

def get_context_data(self, **kwargs):
    # Call the base implementation first to get a context
    context = super().get_context_data(**kwargs)
    today = datetime.datetime.now()
    # Order.objects.filter(created_at__year=today.year, created_at__month=today.month)
    
    context['expense1'] = Tracker.objects.filter(user=self.request.user)


    context['Total1'] =(Body.objects.filter(user=self.request.user, pub_date__year=today.year, pub_date__month=today.month).aggregate(total=Sum(F('price') * F('quantity'))),
 Sport.objects.filter(user=self.request.user, pub_date__year=today.year, pub_date__month=today.month).aggregate(total=Sum(F('price') * F('quantity'))))

    return context

so what I want is , total of body total of sports , which is being asgn to the context "total1" ,and then I want to show it in HTML

my HTML file this is how I am displaying the total,

Total: {{Total1}}

CodePudding user response:

Your oneliner code is a bit confusing but I think I get where you made the mistake - the aggregate returns a dict with the key in the argument as the return value. See below:

body_total = Body.objects.filter(
  user=self.request.user, pub_date__year=today.year, pub_date__month=today.month
).aggregate(total=Sum(F('price') * F('quantity')))['total']

sport_total = Sport.objects.filter(
  user=self.request.user, pub_date__year=today.year, pub_date__month=today.month
).aggregate(total=Sum(F('price') * F('quantity')))['total']

# Note: this is a tuple, not a sum of the two, so check what you need :)
context['Total1'] = (body_total, sport_total)

# For total sum of two totals, just add them of course. 
# It seems like this is what you need from the post, and not the
# line above.
context['Total1'] = body_total   sport_total

PS. the code is not tested. I'm a bit unsure if the F expressions work fine (probably yes). Let me know if there are any issues.

  • Related