Search code examples
pythondjangodjango-queryset

django queryset annotate and order_by. order_by('quantity') splits results


I'm making this queryset in Django. My goal is to list the Top 10 best selling products. The query works and Sum the two products with the same name.

top_10_ordered_products = OrderedProduct.objects.filter(order__in=current_month_orders, vendor=vendor).values('product__product_name').annotate(qty=Sum('quantity')).order_by()

Result:

<QuerySet [{'product__product_name': 'Café Expresso', 'qty': 10}, {'product__product_name': 'Pão de nozes', 'qty': 15}]>

But when adding the order_by('quantity') it separates the summed items in two. One with 10 units and the other with 5.

top_10_ordered_products = OrderedProduct.objects.filter(order__in=current_month_orders, vendor=vendor).values('product__product_name').annotate(qty=Sum('quantity')).order_by('-quantity')

Result:

<QuerySet [{'product__product_name': 'Café Expresso', 'qty': 10}, {'product__product_name': 'Pão de nozes', 'qty': 10}, {'product__product_name': 'Pão de nozes', 'qty': 5}]>

Does anyone know how if it is possible to use the order_by without dismembering the same product_name in the query in these case?


Solution

  • You need to order by your annotated field qty:

    top_10_ordered_products = (
        OrderedProduct.objects.filter(order__in=current_month_orders, vendor=vendor)
        .values("product__product_name")
        .annotate(qty=Sum("quantity"))
        .order_by("-qty")[:10]
    )