Group by 2 fields combination and then order by the sum of each group, multiple annotations django
问题 I was trying to get top products ordered by their total margin sum from invoices as: Filter invoices by given store_id Group by product_name And the get the Sum of gross_margin of each group Finally order them by Sum of gross_margin (high to low) Wrong previous code: high_margin = StoreInvoiceBreakup.objects \ .filter(store_invoice__store_id=store_id) \ .annotate(product_count=Count('product_name')) \ .annotate(gross_margin_sum=Sum('gross_margin')) \ .order_by('-gross_margin_sum') \ .values