0

I want to get sum of all the prices available in my model. I have gone through this link Sum of objects' prices in Django template but I was not able to get my answer when I am running in a shell, I am getting the correct output, but from the template point unable to get the correct output

**shell**


>>> from tasks.models import Task
>>> from django.db.models import Sum
>>> Task.objects.all().aggregate(Sum('price'))
{'price__sum': 2.0}

Model:

from django.db.models import Sum, Avg


class Task(models.Model):
    title = models.CharField(max_length=200)
    complete = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)
    price = models.FloatField(max_length=5,default='0.00',editable=False)

    def __str__(self):
        return self.title


    @property
    def get_price_total(self):
        total=Task.objects.all().aggregate(Avg("price"))
        print(total)
        return total

Views

def query(request):
    tasks = Task.objects.all()


    form = TaskForm()

    if request.method =='POST':
        form=TaskForm(request.POST)
        if form.is_valid():
            form.save()

            return redirect('/')
    print("Price",Task.get_price_total)
    context = {'tasks':tasks,'form':form,'Totalprice':Task.get_price_total}
    return render(request,'tasks/query.html',context)

Output at the console is ( and same is getting printed in the template )

Django version 3.0.7, using settings 'todo.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Price <property object at 0x000002D3301502C0>
[29/Sep/2020 22:33:53] "GET /query/ HTTP/1.1" 200 2473

Can some help me where I am going wrong?

Learner
  • 945
  • 11
  • 23
  • 38

1 Answers1

2

Make get_price_total a classmethod, it does not make sense to be an instance method or property because it aggregates data from all instances of the model.

@classmethod
def get_price_total(cls):
    total = cls.objects.aggregate(total=Sum("price"))['total']
    print(total)
    return total

Then use it in your view/context

context = {'total_price': Task.get_price_total(), ...}
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50
  • 2
    They can also make it property if it is a must: https://stackoverflow.com/questions/128573/using-property-on-classmethods – Selcuk Sep 30 '20 at 02:55
  • @Iain Shelvington Thank you very much, for helping, worked like a charm – Learner Sep 30 '20 at 03:01