Annotated value gives None, need 0

Viewed 44
order_list_cases =(order_list.values('user_id').annotate(dcount=Count('user_id'),customer_paid_sum=(Sum('invoice__transaction_invoice__transaction_amount'))

In this code, the customer_paid_sumis returning None, I want to give it as 0 if it is None. I tried else case along with it but didn't work.

1 Answers

You can work with Coalesce [Django-doc] to return 0 instead of None if the aggregate works over an empty collection:

from django.db.models import Value
from django.db.models.functions import Coalesce

order_list_cases = order_list.values('user_id').annotate(
    dcount=Count('user_id'),
    customer_paid_sum=Coalesce(
        Sum('invoice__transaction_invoice__transaction_amount'),
        Value(0)
    )
)
Related