George
George

Reputation: 169

How to calculate the sum of a property

Hello everyone here is my question:

models.py

class Plant(models.Model)
   nominal_power = models.PositiveIntegerField()
   module_nominal_power= models.PositiveIntegerField()

@property
    def no_modules(self):
       return round(self.nominal_power*1000/self.module_nominal_power)

views.py

def home(request):
    plants = Plant.objects.filter(user=request.user)
    total_power = plants.aggregate(sum=Sum('nominal_power'))
    total_no_modules = plants.aggregate(sum=Sum('no_modules'))['sum']
    template = 'data/home.html'
    context = {'plants':plants,
               'total_power':total_power,
               'total_no_modules':total_no_modules}
    return render(request, template, context)

And I get the error Cannot resolve keyword 'no_modules' into field.Cannot resolve keyword 'no_modules' into field.

I undestand the meaning of the failure but how can I get the total number?

Upvotes: 1

Views: 732

Answers (2)

George
George

Reputation: 169

@Marcin you are correct but I was looking for this:

def home(request):
        plants = Plant.objects.filter(user=request.user)
        total_power = plants.aggregate(sum=Sum('nominal_power'))
        total_no_modules = 0
        for plant in plants
            total_no_modules = total_no_modules + plant.no_modules
        template = 'data/home.html'
        context = {'plants':plants,
                   'total_power':total_power,
                   'total_no_modules':total_no_modules}
        return render(request, template, context)

Upvotes: 0

Marcin Świerczyna
Marcin Świerczyna

Reputation: 112

Maybe use F class

from django.db.models import F
total_no_modules = plants.aggregate(sum=Sum(F('nominal_power')*1000-F('module_nominal_power')))

Upvotes: 2

Related Questions