2

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

and how can i use filter with this
@I'mSRJ: how are you filtering?
i want to filter like this ---> queryset.filter(order__owner=request.user) but your answer is returning dictionary then how can i do it.
ohk i got it---> Invoice.objects.filter(order__owner=request.user).aggregate(total_amount=Sum('order__order_items__amount'),number_of_invoices=Count('pk', distinct=True)) but is there a way that how can I get a queyset as your answer is returning dict

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.