3👍
✅
Try to use annotate with conditional expressions. Your query will look like this:
from django.db.models import Q, F, Sum, Case, When, IntegerField
from django.db.models.functions import Coalesce
cartlist = Cart.objects.annotate(
sum=Coalesce(Sum(Case(
When(Q(carttax__tax__type__name=taxtype) & Q(carttax__tax__tax=tax), then=F('carttax__tax_amount')),
output_field=IntegerField()
)), 0)
)
And in template:
{% for cart in cartlist %}
{{ cart.sum }}
{% endfor %}
Source:stackexchange.com