3👍
✅
I haven’t tested this, but Coalesce
should do the job when the sum aggregation is None.
from django.db.models import Sum, Value
qs = Billing.objects.filter(bill_batch=prev_batch, balance__gt=0) \
.annotate(
payment=Coalesce(
Sum('paidbills__amount_paid', filter=Q(paidbills__pay_period=batch.period)),
Value(0)
)
) \
.order_by('reservation__tenant__name', 'reservation__apt_unit') \
.only('id', 'bill_batch', 'reservation')
Source:stackexchange.com