大家好,我的问题是:
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)
我收到错误无法将关键字'no_modules'解析为字段。无法将关键字'no_modules'解析为字段。
我不明白失败的意义,但我怎样才能获得总数?
答案 0 :(得分:2)
也许使用F class
from django.db.models import F
total_no_modules = plants.aggregate(sum=Sum(F('nominal_power')*1000-F('module_nominal_power')))
答案 1 :(得分:0)
@Marcin你是对的,但我一直在寻找:
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)