django 查询集注释和 order_by。 order_by('quantity') 拆分结果

问题描述 投票:0回答:1

我正在 Django 中制作这个查询集。我的目标是列出前 10 名最畅销的产品。 查询有效并对两个具有相同名称的产品求和。

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

结果:

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

但是在添加 order_by('quantity') 时,它将求和项目一分为二。一个有 10 个单位,另一个有 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')

结果:

<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}]>

有谁知道在这种情况下如何使用 order_by 而不分解查询中的相同 product_name?

python django django-queryset
1个回答
0
投票

您需要按您的注释字段订购

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]
)
© www.soinside.com 2019 - 2024. All rights reserved.