Use Count with aggregate(Sum) in django ORM, Custom Queryset Fields

Viewed 51

I want to use query in which I need No of Invoices and Total Amount of Invoices in a Queryset.

Invoice.objects.aggregate(total_amount=Sum('order__order_items__amount')) 
Invoice.objects.count()

How can I handle above queries in a single query.

1 Answers

You can count the number of distinct primary keys:

from django.db.models import Count, Sum

Invoice.objects.aggregate(
    total_amount=Sum('order__order_items__amount'),
    number_of_invoices=Count('pk', distinct=True)
)

This will return a dictionary with 'total_amount' and 'number_of_invoices' as keys.

Related