1👍
✅
Give this a try
Override you get_queryset() and annotate paper_left
which is the calculated sum of Arrived-Given,
# views.py
from .models import PaperReport
from django.db.models import Sum, F, Case, When, IntegerField
class PaperReportView(ListView):
model = PaperReport
template_name = 'paper_list.html'
def get_queryset(self):
queryset = super().get_queryset()
queryset = queryset.annotate(
paper_left=Sum(
Case(
When(status='Arrived', then=F('amount')),
When(status='Given', then=-F('amount')),
default=0,
output_field=IntegerField(),
)
)
)
return queryset
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['paper_left_sum'] = self.get_queryset().aggregate(Sum('paper_left'))['paper_left__sum']
return context
and in you template file,
<h2>Printer paper left: {{ paper_left_sum }}<h2>
<div>
{% for case in object_list %}
<div>
<p>{{ case.amount }} pcs {{ case.status}} for {{ case.name }}</p>
</div>
{% endfor %}
</div>
Source:stackexchange.com